Quiz: Thread Synchronization in Java: synchronized and Monitors
Study the lesson first: Thread Synchronization in Java: synchronized and Monitors
Total: 9 questions
1. What is thread synchronization in Java, and what is a race condition?
What is thread synchronization in Java, and what is a race condition?
Thread synchronization means coordinating access of several threads to shared data so that only one thread works with it at any given moment. The main tool is the synchronized keyword: a thread acquires the object's monitor, and the others wait. Besides mutual exclusion, synchronized guarantees that changes are visible to the next thread that acquires the same monitor.
A race condition happens when several threads access the same data without synchronization and at least one of the accesses is a write. The classic example is count++: it's three steps (read, add, write back), so two threads doing 100,000 increments each end up with a random number below 200,000 and no exception. The fix is to run the operation under one monitor:
synchronized (lock) {
count++;
}
2. What is the difference between a synchronized method and a synchronized block?
What is the difference between a synchronized method and a synchronized block?
A synchronized instance method is shorthand for a synchronized (this) block around the whole method body: the monitor is the current object. For a static method the monitor is the Class object of its class.
In a synchronized (obj) { ... } block you choose the lock object yourself and protect only the part of the method that needs it. The less code runs under the monitor, the less time other threads spend waiting in line.
Only methods and blocks can be synchronized. For a field, a class or a constructor the compiler reports "modifier synchronized not allowed here": what you protect is not the field but the code that accesses it, and all of that code has to lock on the same object.
3. What is a monitor in Java, and how does synchronized work?
What is a monitor in Java, and how does synchronized work?
A monitor is a mutual-exclusion lock that every object has. synchronized acquires the monitor on entry to the method or block and releases it on exit.
- Only one thread at a time owns a monitor; the others wait for it in the
BLOCKEDstate. - The monitor is released on any exit: after the last statement, on
returnor because of an exception. You don't need to release it by hand, and you can't. - The monitor is reentrant: its owner can enter it again, for example call another
synchronizedmethod of the same object from asynchronizedmethod. The monitor counts the entries and is released when the count drops back to zero. - There is no fairness: which waiting thread gets the monitor next is not guaranteed.
4. Which object should you synchronize on, and which lock objects are dangerous?
Which object should you synchronize on, and which lock objects are dangerous?
A lock object should never change, be reachable by every thread working with the protected data and be unreachable for outside code. The best default is:
private final Object lock = new Object();
thisandMyClass.classare acceptable, but they are public monitors: any code with a reference can lock on them and stall your methods.- A string literal (
"lock"): never. Literals are interned, so another class with the same literal locks on the same object. Integer,Long,Boolean: never. Cached values are shared across the whole JVM, and aftercount++the field refers to a new object, so threads end up on different monitors. Since Java 16 the compiler warns about this (JEP 390).
The general rule: a lock field must be final.
5. Which monitor do static synchronized methods use, and which calls block each other?
Which monitor do static synchronized methods use, and which calls block each other?
A static method has no this, so static synchronized locks on the Class object of its class, the same as synchronized (MyClass.class).
Two threads block each other only when they acquire the monitor of the same object:
synchronizedmethods of one objecta: they block (monitora);- the same method of different objects
aandb: they don't block; - any
static synchronizedmethods of one class: they always block; - a
static synchronizedmethod and a non-staticsynchronizedone: they never block, becauseMyClass.classandthisare different objects; - a
synchronizedmethod and a plain method of the same object: they don't block, because unsynchronized code doesn't check the monitor.
That's why a static field changed by both static and instance methods has to be protected by one monitor, for example MyClass.class everywhere.
6. How does synchronized make changes visible between threads?
How does synchronized make changes visible between threads?
Releasing a monitor happens-before every subsequent acquisition of the same monitor (JLS 17.4.5). Whatever a thread wrote inside synchronized is guaranteed to be visible to another thread that later enters synchronized on the same object.
Without a shared monitor there is no such guarantee: the CPU keeps data in caches and registers, and the JIT compiler may reorder operations and skip re-reading a field. A write by one thread may become visible to another thread late or not at all.
Hence the rule: if a field is changed under a monitor, read it under the same monitor. A synchronized setter with a plain getter doesn't work: the getter is allowed to return a stale value.
7. What is the difference between volatile and synchronized?
What is the difference between volatile and synchronized?
volatile guarantees visibility and ordering, but not mutual exclusion: every read of a volatile field sees the latest write from any thread. Reads and writes of a volatile variable are atomic (including long and double), but compound operations such as count++ are not.
synchronized gives both mutual exclusion and visibility, so it fits compound operations: check-then-act, read-modify-write.
The typical use of volatile is a stop flag that one thread writes and another reads:
private static volatile boolean running = true;
volatile doesn't work for a counter: two threads doing 100,000 count++ each still end up below 200,000. You need synchronized or AtomicInteger.
8. Which methods release the monitor, and which keep it?
Which methods release the monitor, and which keep it?
Only wait() releases a monitor while waiting, and only the monitor of the object it was called on. Before returning, the thread reacquires that monitor, and it keeps holding all other monitors the whole time.
sleep()andyield()keep all monitors.notify()andnotifyAll()keep the monitor: the awakened thread gets it only after the notifying thread leavessynchronized.join()keeps every monitor the waiting thread holds, except the monitor of theThreadobject it was called on: it is implemented withwait()on that object.- Leaving
synchronized, including via an exception, releases the monitor, taking the reentrancy count into account.
That's why Thread objects aren't used as locks and you don't call wait()/notify() on them.
9. How does synchronized work with virtual threads?
How does synchronized work with virtual threads?
The semantics are the same: mutual exclusion, reentrancy, happens-before. The difference was in the implementation.
In Java 21-23, a virtual thread that blocks inside synchronized (sleeps, waits for I/O or calls wait()) gets pinned to its carrier thread and doesn't let go of it. By default there are as many carriers as CPU cores, so thousands of virtual threads asleep under synchronized occupy all of them. The workaround on Java 21 is to replace synchronized around long operations with ReentrantLock.
Java 24 fixed this (JEP 491): virtual threads acquire and release monitors independently of the carrier. The advice not to hold a monitor during slow operations still applies in every version.