Java synchronized Keyword – Complete Guide with Examples
Introduction
The synchronized keyword in Java is used to control access to shared resources when multiple threads are executing concurrently.
Java supports multithreading, which allows multiple threads to execute tasks simultaneously. However, when multiple threads access and modify the same shared variable, unexpected results can occur due to race conditions.
The synchronized keyword helps prevent these problems by allowing only one thread at a time to execute a synchronized method or block protected by the same lock.
It provides two important guarantees:
Mutual Exclusion: Only one thread can hold a particular monitor lock at a time.
Memory Visibility: Changes made by one thread before releasing a monitor become visible to another thread after it subsequently acquires the same monitor.
Why Do We Need synchronized in Java?
Consider a counter variable shared between multiple threads.
When two or more threads increment the same counter simultaneously, the result may be incorrect because the increment operation is not atomic.
For example:
public class Counter {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}The statement count++ involves multiple operations:
Read the current value.
Increment the value.
Write the updated value.
Two threads can read the same value before either writes its update. This can cause a lost update.
To prevent this problem, we can use the synchronized keyword.
Syntax of synchronized in Java
Java supports two common ways to use the synchronized keyword.
1. Synchronized Method
public synchronized void methodName() {
// Thread-safe code
}When a thread calls a synchronized instance method, it acquires the monitor lock of the current object (this).
Other threads attempting to execute synchronized methods using the same object must wait until the lock is released.
2. Synchronized Block
public void methodName() {
synchronized (lockObject) {
// Thread-safe code
}
}A synchronized block allows us to synchronize only a specific section of code.
The thread must acquire the monitor lock associated with the specified object before executing the block.
Example 1: Synchronized Method in Java
In this example, we create a Counter class with a synchronized increment method.
Two threads increment the same counter object.
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
counter.increment();
});
Thread t2 = new Thread(() -> {
counter.increment();
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Final count: " + counter.getCount());
}
}Output:
Final count: 2Explanation:
We create a shared Counter object.
Thread t1 calls the increment() method.
Thread t2 also calls the increment() method.
Since increment() is synchronized, only one thread can execute it at a time on this Counter object.
The second thread waits until the first thread releases the lock.
Finally, the counter value becomes 2.
Example 2: Synchronized Block in Java
A synchronized block is useful when we want to synchronize only a particular section of code instead of an entire method.
public class SynchronizedBlockExample {
private final Object lock = new Object();
private int count = 0;
public void increment() {
synchronized (lock) {
count++;
}
}
public int getCount() {
return count;
}
public static void main(String[] args) {
SynchronizedBlockExample example =
new SynchronizedBlockExample();
Thread t1 = new Thread(() -> {
example.increment();
});
Thread t2 = new Thread(() -> {
example.increment();
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Final count: " + example.getCount());
}
}Output:
Final count: 2Explanation:
We create a private lock object.
Both threads call the increment() method.
The synchronized block acquires the lock object's monitor.
Only one thread can execute the synchronized section at a time.
Once the thread completes the block, it releases the lock.
The next waiting thread can acquire the lock.
Example 3: Synchronized Static Method
A synchronized static method locks the Class object associated with the class rather than an individual object.
It is useful when multiple threads access shared static resources.
public class StaticSyncExample {
private static int count = 0;
public static synchronized void increment() {
count++;
}
public static int getCount() {
return count;
}
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
StaticSyncExample.increment();
});
Thread t2 = new Thread(() -> {
StaticSyncExample.increment();
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Final count: " +
StaticSyncExample.getCount());
}
}Output:
Final count: 2Explanation:
The increment() method is static and synchronized.
The lock is acquired on
StaticSyncExample.class.Only one thread can execute a synchronized static method protected by that class monitor at a time.
The static counter is updated safely.
Example 4: Multiple Threads Incrementing a Counter
The following example demonstrates how synchronized prevents race conditions when multiple threads increment a shared counter repeatedly.
public class ThreadSafeCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
public static void main(String[] args)
throws InterruptedException {
ThreadSafeCounter counter = new ThreadSafeCounter();
int numberOfThreads = 5;
int incrementsPerThread = 100000;
Thread[] threads = new Thread[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < incrementsPerThread; j++) {
counter.increment();
}
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("Expected count: 500000");
System.out.println("Actual count: " + counter.getCount());
}
}Output:
Expected count: 500000
Actual count: 500000Explanation:
Five threads increment the same counter 100,000 times each.
Since the increment() method is synchronized, the shared counter is updated safely.
The final counter value is 500,000.
Difference Between Synchronized Method and Synchronized Block
| Synchronized Method | Synchronized Block |
|---|---|
| Synchronizes the entire method. | Synchronizes a specific section of code. |
| Uses the current object's lock for instance methods. | Uses the specified object's lock. |
| Less flexible. | More flexible. |
| May increase lock contention if the method contains lengthy operations. | Can reduce lock contention by keeping the critical section small. |
| Easy to implement. | Requires an explicit lock object or another suitable monitor. |
Difference Between Instance and Static Synchronization
| Instance Synchronized Method | Static Synchronized Method |
|---|---|
Locks the current object (this). | Locks the Class object. |
| Each object has its own monitor. | One class monitor is shared by all instances of that class. |
| Different instances can execute their synchronized instance methods concurrently. | Static synchronized methods using the same class monitor execute mutually exclusively. |
| Used for instance-level shared resources. | Used for class-level shared resources. |
Without using Join in Thread
When two threads run with a synchronized method or block and
without join(), the worker threads take turns accessing the shared
resource cleanly, while the main thread continues immediately without
waiting for them to finish.
Java Example
In this program, two threads share a single Printer object. The printNumbers
method uses the synchronized keyword so only one thread can run it at a time.
class Printer {
// Only one thread can enter this method at a time
public synchronized void printNumbers(String threadName) {
for (int i = 1; i <= 3; i++) {
System.out.println(threadName + " -> " + i);
try {
Thread.sleep(200); // Pause to simulate work
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class SyncWithoutJoin {
public static void main(String[] args) {
Printer sharedPrinter = new Printer();
Thread t1 = new Thread(() -> sharedPrinter.printNumbers("Thread-1"));
Thread t2 = new Thread(() -> sharedPrinter.printNumbers("Thread-2"));
t1.start();
t2.start();
// Without join(), main does not wait for t1 and t2
System.out.println("Main thread finished!");
}
}
Sample Output
Main thread finished!
Thread-1 -> 1
Thread-1 -> 2
Thread-1 -> 3
Thread-2 -> 1
Thread-2 -> 2
Thread-2 -> 3
(Note: Depending on the OS thread scheduler, Thread-2 might acquire the lock first and
print 1, 2, 3 before Thread-1.)
How It Works
-
Non-blocking
mainthread. Becauset1.join()andt2.join()are omitted,mainprints"Main thread finished!"right after starting the threads. The JVM stays alive until the non-daemon worker threads finish their tasks. -
Mutual exclusion via lock. When
Thread-1entersprintNumbers(), it acquires the intrinsic lock onsharedPrinter.Thread-2enters aBLOCKEDstate and waits untilThread-1finishes the entire loop. -
No interleaved output. Without
synchronized, the numbers from both threads would mix together unpredictably. Withsynchronized, one thread finishes its full sequence before the next thread starts.
Difference Between synchronized and volatile
| synchronized | volatile |
|---|---|
| Provides mutual exclusion and memory visibility. | Provides memory visibility and ordering guarantees. |
| Uses an intrinsic monitor lock. | Does not use a monitor lock. |
| Protects critical sections. | Suitable for certain shared variables. |
| Supports atomic execution of operations inside the protected section. | Does not make compound operations such as count++ atomic. |
| Can cause threads to wait for a lock. | Does not cause monitor-lock waiting. |
Example of volatile:
public class VolatileExample {
private volatile boolean running = true;
public void stop() {
running = false;
}
public void execute() {
while (running) {
// Perform some operation
}
}
}The volatile keyword ensures that changes to the running variable are visible to other threads.
Best Practices for Using synchronized
Keep synchronized blocks as short as possible.
Use private final objects for explicit synchronization locks.
Avoid unnecessary nested synchronized blocks.
Acquire multiple locks in a consistent order to reduce deadlock risks.
Avoid performing lengthy operations while holding a lock.
Use concurrent collections such as ConcurrentHashMap for suitable concurrent data structures.
Use AtomicInteger and other atomic classes when simple atomic operations are required.
Use volatile when visibility is required but mutual exclusion is not necessary.
Always synchronize using the same lock when protecting the same shared mutable state.
Frequently Asked Questions
1. What is the synchronized keyword in Java?
The synchronized keyword is used to control concurrent access to shared resources. It ensures that only one thread at a time can execute code protected by the same monitor lock.
2. Can we use synchronized with static methods?
Yes. A static synchronized method locks the Class object associated with the class.
3. Can a constructor be synchronized in Java?
No. Java does not allow the synchronized keyword in a constructor declaration.
4. Can we use synchronized with variables?
No. The synchronized keyword cannot be applied directly to variables. It can be applied to methods and code blocks.
5. Does synchronized prevent deadlocks?
No. Improper lock acquisition can still cause deadlocks. Consistent lock ordering and careful synchronization design help prevent them.
6. What is the difference between synchronized method and synchronized block?
A synchronized method locks the entire method, whereas a synchronized block locks only a specific section of code.
7. Is synchronized reentrant in Java?
Yes. Java intrinsic locks are reentrant, which means a thread can acquire the same monitor multiple times.
8. Does synchronized guarantee thread safety?
It helps ensure thread safety when all relevant accesses to shared mutable state follow the same synchronization strategy. Using synchronized on only one method does not automatically make every operation on an object thread-safe.
Conclusion
The synchronized keyword is an important Java multithreading concept used to prevent race conditions and protect shared mutable resources.
Java supports synchronized methods, synchronized blocks, and synchronized static methods.
Understanding object monitor locks, reentrant synchronization, memory visibility, and deadlocks helps developers write reliable multithreaded applications.
For more complex concurrency requirements, Java also provides utilities such as ReentrantLock, AtomicInteger, CountDownLatch, and ConcurrentHashMap.

No comments:
Post a Comment