Synchronized
1. What synchronized means in Java
-
Mutual exclusion (mutex). Only one thread at a time may execute the guarded section for the same monitor (lock) object.
-
Visibility / happens‑before. A successful exit from a synchronized section flushes all writes by the current thread to main memory; a successful entrance refreshes the reading thread’s working memory. However, "flushing to main memory" doe not guarantee that other not synchronized threads would not see stale data!
-
Re‑entrancy. The same thread can reacquire the same monitor as many times as needed without blocking itself.
-
Scoping. The monitor you lock is either the current instance (this), the Class object, or an arbitrary reference you supply.
2. All the ways you can apply synchronized
| Syntax | Locks on | Typical use | Behavioural impact |
|---|---|---|---|
public synchronized void foo() { … } | this (the instance monitor) | Protect state that belongs to object instance | Serialises calls on the same instance; different instances still run concurrently |
public static synchronized void bar() { … } | ClassName.class (the class monitor) | Protect static (class‑wide) state | Serialises across all instances of the class |
synchronized(this) { … } | this | Finer‑grained critical section inside a long method | Blocks only the bracketed part, keeps method re‑entrant outside it |
synchronized(someRef) { … } | value of someRef | Coordinate with other code that uses the same reference | Lets you choose exactly which threads contend; wrong choice ⇒ deadlocks or no protection |
synchronized(MyLock.class) { … } | a dedicated Class monitor | Global lock shared by unrelated objects | Handy singleton lock; easily turns into hotspot if over‑used |
private final Object lock = new Object(); … synchronized(lock) { … } | your own private object | Encapsulated lock that callers can’t touch | Avoids external code accidentally blocking on your lock |