HardConcept

What is the difference between synchronized and volatile in Java, and how do you avoid deadlocks?

Technology:
Java
Experience:
Senior

Quick answer

synchronized gives mutual exclusion and memory visibility for a block of code, while volatile only guarantees that reads and writes of one variable are visible to all threads and does not make compound operations such as count++ atomic.

Detailed explanation

Without synchronisation a thread may keep a cached copy of a variable and never see another thread's update. volatile forces reads and writes to go through main memory (and establishes a happens-before relationship), so it is suitable for simple flags such as volatile boolean running. It does not protect count++, which is really read, add, write, and can interleave with another thread.

For compound actions use synchronized, a ReentrantLock, or atomic classes like AtomicInteger and LongAdder, which use compare-and-swap. A deadlock needs four conditions: mutual exclusion, hold and wait, no preemption and circular wait. You prevent it by always acquiring locks in a consistent global order, holding locks for as short a time as possible, using tryLock with a timeout, or avoiding shared mutable state altogether with immutable objects, message passing and higher-level utilities from java.util.concurrent. A thread dump (jstack) reports detected deadlocks.

Example

java
private volatile boolean running = true;     // visibility only
private final AtomicInteger counter = new AtomicInteger();

void work() {
    while (running) {
        counter.incrementAndGet();           // atomic, no lock
    }
}

Key points

  • volatile: visibility, not atomicity
  • synchronized / locks: mutual exclusion and visibility
  • Prevent deadlocks with consistent lock ordering and timeouts
  • JavaMedium

    How does HashMap work internally in Java?

    A HashMap stores entries in an array of buckets; it computes the key's hash code to choose a bucket, resolves collisions with a linked list that becomes a red-black tree when a bucket grows large, and resizes when the load factor of 0.75 is exceeded.

    Mid-level 路 Senior 路 Data Structures
  • JavaHard

    How does JVM memory management and garbage collection work in Java?

    The JVM divides memory into a per-thread stack, a shared heap (split into young and old generations) and Metaspace; the garbage collector frees heap objects that are no longer reachable, collecting short-lived young objects frequently and old objects less often.

    Mid-level 路 Senior 路 Memory Management
  • JavaEasy

    What is the difference between JDK, JRE and JVM in Java?

    The JVM runs Java bytecode, the JRE is the JVM plus the standard libraries needed to run Java programs, and the JDK is the JRE plus the development tools such as the compiler (javac).

    Intern 路 Junior 路 Programming Fundamentals
  • JavaEasy

    What is the difference between == and equals() in Java?

    == compares primitives by value and objects by reference (whether they are the exact same object), while equals() compares the logical content of two objects when the class overrides it.

    Intern 路 Junior 路 Programming Fundamentals