Chapter-4 Flashcards
Desing process for a thread-safe class
-Identify the variables that form the object’s state
-Identify the invariants that constrain the state variables
-Establish a policy for managing concurrent access to the objects’ state
SynchronousQueue
A SynchronousQueue in Java is a special kind of blocking queue where each put operation must wait for a corresponding take, and vice versa — there is no internal capacity (not even one element!).
It’s like a handoff mechanism — a direct exchange of data between two threads.
Latch
A latch is a synchronizer that can delay the progress of threads until it reaches its terminal state.
A latch acts a gate: until the latch reaches the terminal state the gate is closed and no thread can pass, and in terminal state the gate opens, allowing all threads to pass.
Once the latch reaches the terminal state, it cannot change state again, so it remains open forever.
Barriers
Barriers are similar to latches in that they block a group of threads until some event has occurred.
All threads must come together at a barrier point at the same time in order to proceed.
Latches are waiting for events; barriers are for waiting for other threads
It’s the mutable state, stupid.
All concurrency issues boil down to coordinating access to mutable state. The less mutable state, the easier it is to ensure thread safety.
Final fields
Make fields final unless they need to be mutable.
Immutable objects are automatically thread-safe.
Immutable objects simplify concurrent programming tremendously. They are simpler and safer, and can be shared freely without locking or defensive copying.
Encapsulation makes it practical to manage the complexity.
You could write a thread-safe program with all data stored in global variables, but why would you want to? Encapsulating data within objects makes it easier to preserve their invariants; encapsulating synchronization within objects makes it easier to comply with their synchronization policy.
mutable variable
Guard each mutable variable with a lock.
Guard all variables in an invariant with the same lock.
Hold locks for the duration of compound actions.