QuizzesJava Concurrency Utilities
advanced
java

Java Concurrency Utilities

Test your knowledge of ExecutorService, CompletableFuture, atomic classes, concurrent collections, CountDownLatch, Semaphore, and more.

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 Concurrency Utilities. Work through them here, then start the quiz to answer them and see your score.

  1. 1.What is ExecutorService and why use it over raw threads?

    • AA service for managing OS-level threads — it is faster than Java threads
    • BA thread pool abstraction that reuses threads, manages lifecycle, and decouples task submission from execution
    • CA monitoring service for detecting thread deadlocks
    • DA replacement for synchronized that avoids locking
  2. 2.What does this code print?

    import java.util.concurrent.*;
    public class Main {
        public static void main(String[] args) throws Exception {
            ExecutorService exec = Executors.newFixedThreadPool(2);
            Future<Integer> f1 = exec.submit(() -> 10 + 5);
            Future<Integer> f2 = exec.submit(() -> 20 + 3);
            System.out.println(f1.get());
            System.out.println(f2.get());
            exec.shutdown();
        }
    }
    • A23 15
    • B15 23
    • C0 0
    • DCompilation error
  3. 3.What is the difference between Runnable and Callable?

    • ARunnable runs in a thread; Callable runs in the main thread
    • BRunnable is for CPU tasks; Callable is for I/O tasks
    • CRunnable returns void and cannot throw checked exceptions; Callable returns a value and can throw checked exceptions
    • DCallable is newer and deprecated Runnable
  4. 4.What is CompletableFuture?

    • AA future that runs on virtual threads only
    • BA future that automatically completes after a timeout
    • CA thread-safe wrapper around a regular Future
    • DA non-blocking, composable future that allows chaining async operations with thenApply, thenCompose, and exceptionally
  5. 5.What does this code print?

    import java.util.concurrent.*;
    public class Main {
        public static void main(String[] args) throws Exception {
            CompletableFuture<Integer> cf = CompletableFuture
                .supplyAsync(() -> 10)
                .thenApply(n -> n * 2)
                .thenApply(n -> n + 5);
            System.out.println(cf.get());
        }
    }
    • A20
    • B25
    • C15
    • D10
  6. 6.What is AtomicInteger and when should you use it?

    • AAn Integer that is automatically initialised to 0
    • BA thread-safe integer that uses CPU-level compare-and-swap (CAS) for atomic operations without locking
    • CAn integer that triggers a callback when its value changes
    • DAn immutable integer wrapper
  7. 7.What does this code print?

    import java.util.concurrent.atomic.*;
    public class Main {
        public static void main(String[] args) throws InterruptedException {
            AtomicInteger counter = new AtomicInteger(0);
            Thread[] threads = new Thread[100];
            for (int i = 0; i < 100; i++) {
                threads[i] = new Thread(() -> {
                    for (int j = 0; j < 100; j++) counter.incrementAndGet();
                });
                threads[i].start();
            }
            for (Thread t : threads) t.join();
            System.out.println(counter.get());
        }
    }
    • A100
    • B0
    • C10000
    • DSome value less than 10000 due to races
  8. 8.What is CountDownLatch used for?

    • AAllowing one or more threads to wait until a set of operations performed by other threads completes
    • BA thread-safe counter that decrements automatically
    • CLimiting the number of threads that can enter a section
    • DCounting how many threads are currently running
  9. 9.What does this code print?

    import java.util.concurrent.*;
    public class Main {
        public static void main(String[] args) throws InterruptedException {
            CountDownLatch latch = new CountDownLatch(3);
            for (int i = 1; i <= 3; i++) {
                final int id = i;
                new Thread(() -> {
                    System.out.println("Worker " + id + " done");
                    latch.countDown();
                }).start();
            }
            latch.await();
            System.out.println("All workers done");
        }
    }
    • AWorker lines in some order, then All workers done
    • BDeadlock — latch never reaches 0
    • CAll workers done (then worker lines)
    • DOnly "All workers done"
  10. 10.What is a Semaphore?

    • AAn atomic boolean flag for inter-thread communication
    • BA signal sent between threads to coordinate timing
    • CA type of mutex that can only be held by one thread
    • DA counting synchroniser that controls how many threads can access a resource simultaneously
  11. 11.What is ConcurrentHashMap's advantage over synchronised HashMap?

    • AConcurrentHashMap uses less memory than HashMap
    • BConcurrentHashMap is sorted like TreeMap
    • CConcurrentHashMap allows null keys
    • DConcurrentHashMap uses segment/bucket-level locking for writes, allowing concurrent reads and high-throughput updates without full-map locking
  12. 12.What does this code print?

    import java.util.concurrent.*;
    public class Main {
        public static void main(String[] args) throws Exception {
            CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello");
            CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> "World");
            CompletableFuture<String> combined = cf1.thenCombine(cf2, (a, b) -> a + " " + b);
            System.out.println(combined.get());
        }
    }
    • AHello World
    • BHelloWorld
    • CHello
    • DWorld
  13. 13.What is a CyclicBarrier?

    • AA lock that prevents more than N threads from running
    • BA barrier that blocks a single thread until a timeout
    • CA reusable synchronisation point where all threads wait until the required number has arrived, then all proceed together
    • DA replacement for CountDownLatch with auto-reset
  14. 14.What is the ForkJoinPool?

    • AA pool that forks new processes for CPU-intensive tasks
    • BA pool designed for divide-and-conquer tasks — threads can steal work from other threads' queues (work stealing)
    • CA thread pool where threads can join each other's results
    • DA pool used exclusively by CompletableFuture
  15. 15.What does this code print?

    import java.util.concurrent.*;
    public class Main {
        public static void main(String[] args) throws Exception {
            CompletableFuture<String> cf = CompletableFuture
                .supplyAsync(() -> { throw new RuntimeException("oops"); })
                .exceptionally(ex -> "Recovered: " + ex.getMessage());
            System.out.println(cf.get());
        }
    }
    • AThrows RuntimeException
    • Bnull
    • CRecovered: oops
    • DRecovered: java.lang.RuntimeException: oops
  16. 16.What is the difference between submit() and execute() on ExecutorService?

    • Aexecute() can throw checked exceptions; submit() cannot
    • Bsubmit() runs synchronously; execute() runs asynchronously
    • Csubmit() returns a Future (result/exception tracking); execute() is fire-and-forget with no return value
    • Dexecute() is for Callable; submit() is for Runnable
  17. 17.What does shutdown() vs shutdownNow() do on an ExecutorService?

    • Ashutdown() kills all threads immediately; shutdownNow() waits for tasks to finish
    • BThey are identical
    • Cshutdown() stops accepting new tasks and waits for running tasks to finish; shutdownNow() attempts to interrupt running tasks and returns pending tasks
    • Dshutdown() only affects idle threads; shutdownNow() affects all threads
  18. 18.What is a BlockingQueue's role in a producer-consumer pattern?

    • AIt notifies producers when consumers are slow
    • BIt blocks both producers and consumers permanently
    • CIt converts synchronous tasks to asynchronous
    • DProducer threads put() items (blocking when full); consumer threads take() items (blocking when empty) — the queue handles all synchronisation
  19. 19.What does this code print?

    import java.util.concurrent.*;
    public class Main {
        public static void main(String[] args) throws Exception {
            ExecutorService exec = Executors.newFixedThreadPool(3);
            CountDownLatch latch = new CountDownLatch(5);
            for (int i = 1; i <= 5; i++) {
                final int id = i;
                exec.submit(() -> {
                    latch.countDown();
                    return id * 10;
                });
            }
            latch.await();
            exec.shutdown();
            System.out.println("All 5 tasks submitted and counted down");
        }
    }
    • AOnly 3 tasks complete — others are dropped
    • BDeadlock — 5 tasks but only 3 threads
    • CAll 5 tasks submitted and counted down
    • DCompilation error
  20. 20.What is Exchanger in java.util.concurrent?

    • AA mechanism for exchanging messages between JVMs
    • BA utility for swapping variable names at runtime
    • CAn alternative to CompletableFuture for two-stage pipelines
    • DA synchronisation point where two threads swap objects — each thread blocks at exchange() until the other arrives