CodeGym /Courses /JAVA 25 SELF /synchronized, volatile: syntax and usage

synchronized, volatile: syntax and usage

JAVA 25 SELF
Level 52, Lesson 1
Available

1. The synchronized keyword: why and how

In Java, the synchronized keyword is like a sign reading “Occupied!” on a restroom door: while one thread is inside the “critical section,” the others politely wait their turn. Only when the first exits can the next enter and run its code.

Syntax: block and method

Synchronized block

synchronized (object) {
    // critical section
}
  • object is any object you want to lock on. While one thread executes this block, other threads that also want to enter a block with the same object will wait.

Synchronized method

public synchronized void increment() {
    // critical section
}
  • Here, the “lock” is placed on the object itself (this). That means only one thread at a time can execute any synchronized method of this object.

Static synchronized method

public static synchronized void foo() {
    // critical section
}
  • Here, locking happens at the class level (ClassName.class), not on a specific instance.

How it works under the hood

When a thread enters a synchronized block or method, it acquires the object’s monitor (or the class’s monitor for static methods). If the monitor is already taken, the thread waits. As soon as the monitor is released, the next thread can enter.

2. Example: incrementing a counter with and without synchronization

Without synchronization

public class Counter {
    private int count = 0;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}
public class CounterDemo {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Final value: " + counter.getCount());
    }
}

Expected value: 2000
Actual value: it can be lower (for example, 1995, 1987...), and each run brings its own “surprise.”

Why? Because the operation count++ is not atomic: it’s split into three actions — read the value, increment it, write it back. If two threads do this at the same time, they can overwrite each other’s results.

Solution: synchronized

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

Now only one thread at a time can execute increment(). The final value will always be 2000.

Alternative: synchronized block

public class Counter {
    private int count = 0;

    public void increment() {
        synchronized (this) {
            count++;
        }
    }
}

The result will be the same. You can synchronize not the entire method but only the necessary part.

3. Introduction to the “object monitor”

A monitor is a “lock” built into every object in Java. When you write synchronized(object), the thread tries to “lock” that object. If the lock is free, the thread acquires it; if not, it waits its turn. As soon as the thread exits the block, the lock is released.

Important! If you synchronize on different objects, threads will not wait for each other. Therefore, it’s crucial to choose the correct object for synchronization.

Static synchronized methods

Sometimes the shared resource is not an instance but something common to all instances of the class (for example, a static variable). In this case, synchronization must be at the class level.

public class StaticCounter {
    private static int count = 0;

    public static synchronized void increment() {
        count++;
    }

    public static int getCount() {
        return count;
    }
}

This is equivalent to:

public static void increment() {
    synchronized (StaticCounter.class) {
        count++;
    }
}

The monitor is attached to the Class object, not to a specific instance.

4. The volatile keyword: what it is and why

The visibility problem between threads

In Java, each thread can cache variable values to speed things up. This means that if one thread changes a variable, another thread might “not notice,” continuing to read the value from its local cache. This is especially critical for flags that threads use to signal each other.

How volatile works

If a variable is declared volatile, it means:

  • All threads read from and write to main memory, bypassing caches.
  • Any change to the variable becomes immediately visible to all threads.

But! Operations on a volatile variable are not atomic by themselves (except for simple reads/writes of primitives like boolean, int, etc.). If you do anything more complex than assignment, you need synchronization.

Example: a shutdown flag

public class Worker extends Thread {
    private volatile boolean running = true;

    public void run() {
        while (running) {
            // doing something useful
        }
        System.out.println("Thread terminated");
    }

    public void shutdown() {
        running = false;
    }
}
Worker w = new Worker();
w.start();
// ... some time later
w.shutdown();

Without volatile, the thread may “not notice” the flag change and spin forever (especially on multi-core systems). With volatile, everything works as expected.

5. Limitations of volatile: non-atomicity

Many beginners think: “If I make an int volatile, I can write count++ and not worry.” Unfortunately, that’s not the case:

private volatile int count = 0;

public void increment() {
    count++;
}

Error! The operation count++ is still not atomic — it has three steps: (1) read, (2) increment, (3) write back. If two threads read the same value simultaneously, both increment it and both write the same result — one increment gets “lost.”

Conclusion: volatile ensures visibility of changes only; it does not protect against races in compound operations.

6. When to use synchronized and when — volatile

  • volatile — when you have a simple flag (for example, a boolean) that one thread writes and another reads. Example: shutting down a thread, signaling an event.
  • synchronized — when you need atomicity for compound operations (for example, an increment, updating multiple variables, working with data structures).

Quick reference table

Scenario volatile synchronized
Signal passing between threads ✔ ✔
Atomic operation (increment) ✖ ✔
Multiple steps in a critical section ✖ ✔
Visibility only ✔ ✔

7. Common mistakes when using synchronized and volatile

Error #1: Synchronizing on the wrong object. If you synchronize on a local variable or on a different object in each thread, you get no protection.

Object lock = new Object();
synchronized (lock) {
    // ...
}

If each thread creates its own lock, it’s useless. You need a single synchronization point — a shared object for all threads.

Error #2: Expecting atomicity from volatile. volatile guarantees visibility, not atomicity. Operations like count++ are still unsafe without synchronization.

Error #3: Synchronizing too large a region of code. If you synchronize the entire method when only one line is needed, you unnecessarily block other threads and lose performance. Try to minimize the “critical section.”

Error #4: Forgot to make synchronization “static” for static data. If you have a static variable but synchronize on this, that won’t help. Static data requires class-level synchronization: synchronized(ClassName.class).

Error #5: Synchronizing on a string literal. Synchronizing on strings is dangerous because identical literals are interned by the JVM. You can accidentally get a shared lock for different parts of the program.

1
Task
JAVA 25 SELF, level 52, lesson 1
Locked
Public Charity Donations Accounting 🌍
Public Charity Donations Accounting 🌍
1
Task
JAVA 25 SELF, level 52, lesson 1
Locked
Managing the background security service 🛡️
Managing the background security service 🛡️
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION