QuizzesJava Synchronization
advanced
java

Java Synchronization

Master synchronized blocks, locks, volatile, deadlocks, wait/notify, and thread-safe design patterns in Java.

25 minutes 20 questions Pass at 70%
Time Limit
25 minutes - timer starts when you begin
Change Answers Freely
Revisit and change any answer before submitting
Full Review After Submit
Correct answers and explanations shown for every question
Auto-submit on timeout
Quiz submits automatically when time runs out

Questions in this quiz

20 questions on Java Synchronization. Work through them here, then start the quiz to answer them and see your score.

  1. 1.What does the synchronized keyword guarantee?

    • AThe method runs in a separate thread
    • BOnly one thread at a time can execute the synchronized block or method on the same monitor object
    • CAll threads run the block simultaneously but in order
    • DThe method cannot throw exceptions
  2. 2.What does this code print when two threads call increment() simultaneously?

    public class SafeCounter {
        private int count = 0;
        public synchronized void increment() { count++; }
        public synchronized int getCount() { return count; }
    }
    // Thread A and Thread B each call increment() 1000 times
    • ASome value less than 2000 due to race condition
    • BAlways 1000
    • CAlways exactly 2000
    • DCompilation error — synchronized not allowed on instance methods
  3. 3.What is the monitor (intrinsic lock) in Java?

    • AA special class in java.util.concurrent
    • BEvery Java object implicitly has a monitor — a built-in lock used by synchronized blocks and methods
    • CA thread that watches other threads for errors
    • DA JVM tool for monitoring thread activity
  4. 4.What is a deadlock?

    • AWhen a thread takes too long to execute
    • BWhen a thread holds a lock for too long
    • CWhen synchronized is used without a shared object
    • DWhen two or more threads are each waiting for a lock held by another, creating a circular wait with no progress
  5. 5.What does this code risk?

    class Main {
        static Object lock1 = new Object();
        static Object lock2 = new Object();
        static void methodA() {
            synchronized(lock1) {
                synchronized(lock2) { /* work */ }
            }
        }
        static void methodB() {
            synchronized(lock2) {
                synchronized(lock1) { /* work */ }
            }
        }
    }
    • ACompilation error — cannot nest synchronized blocks
    • BRace condition on lock1 and lock2
    • CLivelock — threads keep retrying forever
    • DDeadlock — methodA acquires lock1 then lock2; methodB acquires lock2 then lock1 — opposite order risks circular wait
  6. 6.What does the volatile keyword do?

    • AEnsures reads and writes to a variable go directly to main memory, providing visibility across threads but not atomicity
    • BMakes a variable thread-safe for compound operations like increment
    • CMakes the variable immutable after first assignment
    • DPrevents the variable from being garbage collected
  7. 7.What does this code demonstrate?

    public class StopFlag {
        private volatile boolean running = true;
        public void stop() { running = false; }
        public void run() {
            while (running) {
                // do work
            }
            System.out.println("Stopped");
        }
    }
    • AA deadlock — the while loop blocks forever
    • BCorrect use of volatile — the worker thread will always see running=false when stop() is called from another thread
    • CUnnecessary — the JVM always reads fresh values without volatile
    • DA race condition — volatile does not work for booleans
  8. 8.What is wait() and notify() used for?

    • AInter-thread communication — wait() releases the monitor and suspends; notify() wakes one waiting thread
    • BPausing and resuming threads based on priority
    • CChecking if a thread is alive before calling it
    • DReplacing synchronized with a lighter alternative
  9. 9.What does this code print?

    public class Main {
        static final Object lock = new Object();
        static boolean ready = false;
        public static void main(String[] args) throws InterruptedException {
            Thread waiter = new Thread(() -> {
                synchronized (lock) {
                    while (!ready) {
                        try { lock.wait(); } catch (InterruptedException e) {}
                    }
                    System.out.println("Waiter: ready!");
                }
            });
            waiter.start();
            Thread.sleep(100);
            synchronized (lock) {
                ready = true;
                lock.notify();
            }
            waiter.join();
        }
    }
    • ANothing — waiter sleeps forever
    • BCompilation error
    • CWaiter: ready!
    • DDeadlock between waiter and main
  10. 10.What is a synchronized block versus a synchronized method?

    • AThere is no practical difference
    • Bsynchronized methods are deprecated in favour of blocks
    • Csynchronized methods lock the entire object; synchronized blocks can lock on any object and can be scoped to a smaller critical section
    • Dsynchronized blocks are faster; synchronized methods are safer
  11. 11.What is livelock?

    • AWhen a single thread holds a lock forever
    • BWhen threads keep responding to each other's state changes and stay busy but make no actual progress
    • CWhen threads run too fast and overwhelm the CPU
    • DA form of deadlock where threads are blocked
  12. 12.What does this code print?

    public class Main {
        private static int x = 0;
        private static int y = 0;
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Thread(() -> { x = 1; y = 2; });
            Thread t2 = new Thread(() -> {
                System.out.println("y=" + y + " x=" + x);
            });
            t1.start(); t1.join();
            t2.start(); t2.join();
        }
    }
    • Ay=2 x=1 — join() ensures happens-before visibility
    • BNon-deterministic — could be any combination
    • Cy=0 x=0 — t2 sees stale values
    • Dy=2 x=0 — partial visibility
  13. 13.What is the happens-before relationship in Java memory model?

    • AA compile-time ordering of instructions
    • BA rule that higher-priority threads always run before lower-priority ones
    • CA guarantee that all writes before a synchronisation action are visible to all reads after the corresponding synchronisation action
    • DA guarantee that code runs in the order it is written
  14. 14.What is starvation in concurrent programming?

    • AWhen a thread is perpetually denied access to a resource because other threads are always given priority
    • BWhen a thread consumes too much CPU and slows others
    • CWhen too many threads try to access the same data
    • DWhen a thread waits for I/O that never arrives
  15. 15.What does synchronized on a static method lock on?

    • AThe first instance created of that class
    • BThe current thread
    • CA shared global JVM lock
    • DThe Class object of the declaring class
  16. 16.What does this code demonstrate?

    public class Singleton {
        private static volatile Singleton instance;
        private Singleton() {}
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    • AA thread-safe Singleton that is inefficient due to always synchronising
    • BA Singleton with a race condition on the first null check
    • CAn incorrect Singleton — double-checking is not thread-safe
    • DDouble-checked locking — a thread-safe lazy Singleton using volatile and synchronized together
  17. 17.Can a thread call wait() outside a synchronized block?

    • AYes, but it has no effect outside synchronized
    • BNo, calling wait() without owning the monitor throws IllegalMonitorStateException
    • COnly if the thread has the highest priority
    • DYes, wait() works anywhere
  18. 18.What is a reentrant lock?

    • AA lock that the same thread can acquire multiple times without deadlocking itself
    • BA lock that can be acquired by multiple threads simultaneously
    • CA lock that times out after a set period
    • DA lock that automatically retries if acquisition fails
  19. 19.What does this code print?

    public class Main {
        synchronized void outer() {
            System.out.println("outer");
            inner();
        }
        synchronized void inner() {
            System.out.println("inner");
        }
        public static void main(String[] args) {
            new Main().outer();
        }
    }
    • Aouter inner
    • Bouter (deadlock prevents inner from running)
    • CCompilation error
    • Dinner outer
  20. 20.What is the main advantage of ReentrantLock over synchronized?

    • Asynchronized causes deadlocks; ReentrantLock does not
    • BReentrantLock works across multiple JVMs
    • CReentrantLock is always faster than synchronized
    • DReentrantLock offers tryLock(), timed locking, interruptible locking, fairness, and multiple Conditions