Skip to content

Instantly share code, notes, and snippets.

@ajmurmann
Created September 12, 2017 05:10
Show Gist options
  • Save ajmurmann/88b66b4f22a8f223cd1c0b67b66361ff to your computer and use it in GitHub Desktop.
Save ajmurmann/88b66b4f22a8f223cd1c0b67b66361ff to your computer and use it in GitHub Desktop.

Chapter 4: Composing Objects

  1. Identify variables that form state
  2. Identify invariants
  3. Policy for concurrent access to state (synchronization policy)
  • Synchronization Policy preserves invariants and post-conditions
  • Final allows to reduce state space
  • Illegal states need to be prevented by synchronizing involved variables

4.1.2

State dependent operations may have pre-conditions. In concurrent apps they may wait till those become true

  • can be done using wait and notify
  • better use built-inn synchronizers such as Semaphore or BlockingQueue

TODO: See if awaitility uses this

4.1.3

What variables does my class own?

  • Returned mutual references -> shared ownership
  • Passed objects usually mean also shared ownership

4.2 Confinement

  • Confinement of ownership to class makes it easier to understand and thus control how it's accessed
  • References to objects still means the referenced object being mutable

4.2.1 Java Monitor Pattern

  • Pattern: object state guarded with intrinsic lock (listing 4.1)
  • better: use private lock object -> easier to prevent lock object from escaping -> easier debugging (listing 4.3)

4.2.2 - 4.3.1

  1. Use monitor pattern to implement vehicle fleet
  2. Improve by using thread safe data structures
  • ImmutablePoint
  • ConcurrentHashMap
  • Collections.unmodifiableMap (live updates) (alternatively could return shallow copy b/c points are safe now)

4.3.2 Lock independent states with independent locks

4.3.3

Making variable alone thread-safe is not enough if the variable is part of a invariant that includes other variables

4.3.4 Publishing underlying state variables

"If a state variable is thread-safe, does not participate in any invariants that constrain its value, and has no prohibited state transitions for any of its operations, then it can safely be published" Why would I want to do this? Wouldn't it be better to just always make changes explicit or return immutable objects?

4.4 Modifying existing classes

  • Modifying existing classes is safer b/c it's all in the same source file
  • Inheritance might not be possible b/c Java's shitty inheritance model
  • 4.4.1 Write helper that adds method and uses same lock as existing class (if we can get a hold of it) why would I do this?
  • 4.4.2 use proper composition and delegate all calls like a normal person

4.5 Documentation

  • Document thread-safety guarantees for users
  • Document synchronization policy for maintainers
  • When reading vague documentation try to see spec from implementor perspective
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment