- Identify variables that form state
- Identify invariants
- 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
State dependent operations may have pre-conditions. In concurrent apps they may wait till those become true
- can be done using
wait
andnotify
- better use built-inn synchronizers such as
Semaphore
orBlockingQueue
TODO: See if awaitility uses this
What variables does my class own?
- Returned mutual references -> shared ownership
- Passed objects usually mean also shared ownership
- 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
- 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)
- Use monitor pattern to implement vehicle fleet
- Improve by using thread safe data structures
- ImmutablePoint
- ConcurrentHashMap
- Collections.unmodifiableMap (live updates) (alternatively could return shallow copy b/c points are safe now)
Making variable alone thread-safe is not enough if the variable is part of a invariant that includes other 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?
- 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
- Document thread-safety guarantees for users
- Document synchronization policy for maintainers
- When reading vague documentation try to see spec from implementor perspective