![]() |
VOOZH | about |
Synchronization in Java is used to control access to shared resources in a multithreaded environment. It ensures that only one thread executes a critical section at a time, preventing data inconsistency.
Synchronization in Java can be applied in different ways depending on the level of control required. It helps manage thread access to shared resources efficiently.
To synchronize a method, add the synchronized keyword. This ensures that only one thread can execute the method at a time.
Example: Unsynchronized Method
Output:
0
0
1
2
1
2
Explanation: Threads t1 and t2 access the method concurrently, causing mixed output.
Example: Synchronized Method
0 1 2 0 1 2
Explanation: Only one thread executes the method at a time, ensuring data consistency.
Block synchronization is used when only part of a method contains critical code. This improves performance by allowing threads to execute non-critical code concurrently.
Example: Synchronized Block
Mohit
Explanation: Only the block updating name and count is synchronized. Adding names to the list runs concurrently.
| Feature | Method Synchronization | Block Synchronization |
|---|---|---|
| Scope | Locks the entire method | Locks only the specific block of code |
| Performance | Can cause unnecessary blocking for non-critical code | More efficient, only critical sections are synchronized |
| Lock | Acquires the lock on the method’s object | Acquires the lock on the object or class specified in the block |
| Flexibility | Less flexible, entire method is locked | More flexible, allows selective synchronization |