Skip to main content

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

SyntaxLocks onTypical useBehavioural impact
public synchronized void foo() { … }this (the instance monitor)Protect state that belongs to object instanceSerialises calls on the same instance; different instances still run concurrently
public static synchronized void bar() { … }ClassName.class (the class monitor)Protect static (class‑wide) stateSerialises across all instances of the class
synchronized(this) { … }thisFiner‑grained critical section inside a long methodBlocks only the bracketed part, keeps method re‑entrant outside it
synchronized(someRef) { … }value of someRefCoordinate with other code that uses the same referenceLets you choose exactly which threads contend; wrong choice ⇒ deadlocks or no protection
synchronized(MyLock.class) { … }a dedicated Class monitorGlobal lock shared by unrelated objectsHandy singleton lock; easily turns into hotspot if over‑used
private final Object lock = new Object(); … synchronized(lock) { … }your own private objectEncapsulated lock that callers can’t touchAvoids external code accidentally blocking on your lock