Java
Module 22: Java SynchronizationBeginner26 min read

Race Conditions, Synchronized, Volatile & Deadlocks

Ensure thread safety using synchronized methods/blocks, ReentrantLock, AtomicInteger, volatile visibility, and deadlock prevention.

Key Takeaways & Core Concepts
  • `wait()`, `notify()`, `notifyAll()`: Must be called inside a synchronized block on the lock object. Always call wait() inside a while (!condition) loop (not if) to guard against spurious wakeups.
  • Deadlock Prevention: A deadlock occurs when Thread A holds Lock 1 waiting for Lock 2 while Thread B holds Lock 2 waiting for Lock 1. Break circular wait by always acquiring locks in a consistent global order or using ReentrantLock.tryLock().

Race Conditions & CPU Caching

Modern CPUs cache variables in L1/L2 core caches and may reorder instructions. Without synchronization, two threads executing count++ concurrently suffer lost updates because count++ is three separate steps (read, add 1, write), and one thread may not even see another thread's latest write (visibility bug).

Lock-Free Thread Safety with AtomicInteger
1import java.util.concurrent.atomic.AtomicInteger;
2
3public class Main {
4 public static void main(String[] args) throws InterruptedException {
5 AtomicInteger counter = new AtomicInteger(0);
6 Runnable task = () -> {
7 for (int i = 0; i < 1000; i++) counter.incrementAndGet();
8 };
9 Thread t1 = new Thread(task);
10 Thread t2 = new Thread(task);
11 t1.start(); t2.start();
12 t1.join(); t2.join();
13 System.out.println("Final Count: " + counter.get());
14 }
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: `t1.join()` and `t2.join()` ensure the main thread waits until both workers finish before printing.

synchronized vs volatile vs AtomicInteger

MechanismVisibilityAtomicityBlocking
volatileYes (reads/writes main memory, happens-before)No (unsafe for count++)Lock-free
synchronizedYesYes (mutual exclusion via monitor)Blocking
ReentrantLockYesYes (supports tryLock(timeout), fairness)Blocking / Try
AtomicIntegerYesYes (hardware Compare-And-Swap)Lock-free

Inter-Thread Communication & Deadlocks

  • `wait()`, `notify()`, `notifyAll()`: Must be called inside a synchronized block on the lock object. Always call wait() inside a while (!condition) loop (not if) to guard against spurious wakeups.
  • Deadlock Prevention: A deadlock occurs when Thread A holds Lock 1 waiting for Lock 2 while Thread B holds Lock 2 waiting for Lock 1. Break circular wait by always acquiring locks in a consistent global order or using ReentrantLock.tryLock().
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)