Learn Java
import com.learnjava.advancedjava.ThreadSynchronization;

Thread Synchronization & Locks in Java

@Concept

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.

@HowItWorks
1

The synchronized keyword

Ensures only one thread at a time can execute a given block or method, acquiring a lock on a specific object.

2

Automatic lock release

synchronized automatically releases its lock once the block or method finishes, even if an exception is thrown partway through.

3

What synchronization prevents

A race condition, where multiple threads modifying the same shared data concurrently with no coordination produce an unpredictable result.

4

java.util.concurrent.locks.Lock

A more flexible, explicit alternative, with separate lock() and unlock() calls and a non-blocking tryLock() option.

5

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.

@Example
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);
}
}
Output
Final count: 2000
1increment() is declared synchronized, so only one thread at a time can actually execute count++ inside it.
2t1 and t2 both call increment() 1000 times each, concurrently, from two separate threads.
3Because synchronized prevents any overlap, no increment is ever lost to a race condition between the two threads.
4join() on both threads ensures main waits for both to fully finish before printing, correctly showing the full, accurate total of 2000.
@UseCases
Making a shared counter or accumulator safe to update from multiple threads at once
Protecting a critical section of code so only one thread can execute it at a time
Choosing java.util.concurrent.locks.Lock over synchronized when tryLock's non-blocking behavior is specifically needed
Debugging a lost-update bug caused by unsynchronized concurrent access to shared, mutable data

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Java yourself — building beats watching.