Chapter 2. Thread Safety
informally, an object's state is its data, stored in state variables such as instance or static fields.
Copy
If multiple threads access the same mutable state variable without appropriate synchronization, your program is
broken. There are three ways to fix it:
x Don't share the state variable across threads;
x Make the state variable immutable; or
x Use synchronization whenever accessing the state variable.
Copy
When designing thread?safe classes, good object-oriented techniques encapsulation, immutability, and clear
specification of invariants are your best friends.
Copy
A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling orinterleaving of the execution of those threads by the runtime environment, and with no additional synchronization or
other coordination on the part of the calling code.
Intrinsic Locks
A synchronized block has two parts: a reference to an object that will serve as the lock, and a block of code to be
guarded by that lock. A synchronized method is shorthand for a synchronized block that spans an entire method
body, and whose lock is the object on which the method is being invoked. (Static synchronized methods use the Class
object for the lock.)
Reentrancy
When a thread requests a lock that is already held by another thread, the requesting thread blocks. But because
intrinsic locks are reentrant, if a thread tries to acquire a lock that it already holds, the request succeeds. Reentrancy
means that locks are acquired on a per-thread rather than per-invocation basis. [7] Reentrancy is implemented by
associating with each lock an acquisition count and an owning thread. When the count is zero, the lock is considered
unheld. When a thread acquires a previously unheld lock, the JVM records the owner and sets the acquisition count to
one. If that same thread acquires the lock again, the count is incremented, and when the owning thread exits the
synchronized block, the count is decremented. When the count reaches zero, the lock is released