Thread Synchronization & Locks in Java
The synchronized keyword ensures only one thread at a time can execute a given block of code, or a given method, acquiring a lock on a specific object before entering and releasing it automatically on exit. Any other thread that tries to enter that same synchronized section while the lock is held simply waits until it's released. This directly prevents the race conditions unsynchronized concurrent access to shared, mutable data can cause: a synchronized increment method makes count++ genuinely safe to call from multiple threads at once, where an unsynchronized version could lose updates when two threads happen to read the same value before either has written its own increment back.
java.util.concurrent.locks.Lock offers a more flexible, explicit alternative to synchronized, with tryLock(), attempting to acquire a lock without blocking indefinitely if unavailable, and separate lock() and unlock() calls giving finer control than synchronized's automatic block-scoped locking allows — at the cost of needing to remember to release the lock manually, typically inside a finally block, since it won't happen automatically the way synchronized's does.
The synchronized keyword
Ensures only one thread at a time can execute a given block or method, acquiring a lock on a specific object.
Automatic lock release
synchronized automatically releases its lock once the block or method finishes, even if an exception is thrown partway through.
What synchronization prevents
A race condition, where multiple threads modifying the same shared data concurrently with no coordination produce an unpredictable result.
java.util.concurrent.locks.Lock
A more flexible, explicit alternative, with separate lock() and unlock() calls and a non-blocking tryLock() option.
Manual unlock with Lock
Since it isn't automatic like synchronized, unlock() needs to be called explicitly, typically inside a finally block to guarantee it happens.
public class SynchronizationDemo { static int count = 0; static synchronized void increment() { count++; } public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) increment(); }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) increment(); }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Final count: " + count); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.