Practice: Concurrency & JVM Drill
50 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A technical round mixes topics fast: a one-line definition, a buggy snippet to fix, a producer-consumer to write, a "draw the memory" question. The interviewer is checking speed, exact wording and whether you can name cause, fix and reason.
Round 1: rapid-fire concurrency and JVM questions
Rapid-fire answer is a one-sentence definition followed by one detail that shows depth, then you stop. It is what an interviewer wants when questions come quickly.
Rapid-fire rounds reward short, exact answers. Give the definition in one sentence, add one detail, and stop. If you are unsure, say what you do know rather than guessing.
import java.util.Arrays;
public class RapidFireSnip { public static void main(String[] args) { System.out.println(Arrays.toString(Thread.State.values())); Thread t = new Thread(() -> {}); System.out.println(t.getState() + " " + t.isDaemon() + " " + t.getPriority()); System.out.println(String.class.getClassLoader() == null); }}[NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED] NEW false 5 true
Round 2: fix three buggy concurrent snippets
Lost update is a bug where two threads read, change and write the same value, so one write overwrites the other. Check-then-act is the same family: another thread acts between the test and the action.
Each bug has the same three-part answer: cause, fix, why the fix works. Three programs fix a lost-update counter, a check-then-act on a shared map, and double-checked locking.
Example 1 · Bug 1 fixed: lost updates on a shared counter
import java.util.concurrent.atomic.AtomicInteger;
public class FixCounterDemo { // Bug: static int downloads; downloads++ from many threads loses updates static final AtomicInteger downloads = new AtomicInteger();
public static void main(String[] args) throws InterruptedException { Thread[] users = new Thread[4]; for (int i = 0; i < users.length; i++) { users[i] = new Thread(() -> { for (int k = 0; k < 25_000; k++) downloads.incrementAndGet(); }); users[i].start(); } for (Thread u : users) u.join(); System.out.println("downloads = " + downloads.get()); }}downloads = 100000
What this code does
- With
static int downloadsanddownloads++, four threads lose updates because++is read-add-write.AtomicInteger.incrementAndGet()makes each increment one atomic step, so the total is always 100000. - Say why not
volatile: it would make writes visible but++would still lose updates.
Example 2 · Bug 2 fixed: check-then-act on a shared map
import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;
public class FixCheckThenActDemo { static final AtomicInteger profilesBuilt = new AtomicInteger();
static String buildProfile(String user) { profilesBuilt.incrementAndGet(); return "profile of " + user; }
public static void main(String[] args) throws InterruptedException { // Bug: if (!cache.containsKey(u)) cache.put(u, buildProfile(u)); on a HashMap Map<String, String> cache = new ConcurrentHashMap<>(); Runnable visit = () -> { for (int i = 0; i < 1000; i++) { cache.computeIfAbsent("asha", FixCheckThenActDemo::buildProfile); } }; Thread a = new Thread(visit); Thread b = new Thread(visit); a.start(); b.start(); a.join(); b.join(); System.out.println(cache.get("asha") + ", built " + profilesBuilt.get() + " time(s)"); }}profile of asha, built 1 time(s)
What this code does
if (!cache.containsKey(u)) cache.put(u, build(u))on aHashMaplets two threads both see "missing" and build twice (and can corrupt theHashMap).ConcurrentHashMap.computeIfAbsentchecks and inserts atomically, so the profile is built exactly once however many threads ask.
Example 3 · Bug 3 fixed: double-checked locking with volatile
import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CountDownLatch;
class AppConfig { private static volatile AppConfig instance; static int created = 0;
private AppConfig() { created++; }
static AppConfig getInstance() { AppConfig local = instance; if (local == null) { // first check, no lock synchronized (AppConfig.class) { local = instance; if (local == null) { // second check, with lock instance = local = new AppConfig(); } } } return local; }}
public class FixSingletonDemo { public static void main(String[] args) throws InterruptedException { Set<AppConfig> seen = ConcurrentHashMap.newKeySet(); CountDownLatch go = new CountDownLatch(1); Thread[] threads = new Thread[8]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(() -> { try { go.await(); } catch (InterruptedException e) { return; } seen.add(AppConfig.getInstance()); }); threads[i].start(); } go.countDown(); for (Thread t : threads) t.join(); System.out.println("distinct instances: " + seen.size() + ", constructor ran: " + AppConfig.created); }}distinct instances: 1, constructor ran: 1
What this code does
- Eight threads start together and all call
getInstance(); only one creates the object, so there is one instance and one constructor call. - The
volatileoninstanceis the fix: it stops other threads from seeing a half-constructed object through the first, unlocked check.
Double-checked locking needs volatile because instance = new AppConfig() is not one step: without it, another thread can see a non-null reference to an object whose constructor has not finished. The simpler interview answer is the holder idiom or an enum singleton, both thread-safe by class-initialisation rules.
Find the bug
Find the concurrency bug
Click the line that causes the bug.
Four threads call this. The total is sometimes too low. Which line is wrong?
Round 1 of 3Round 3: producer-consumer with BlockingQueue
BlockingQueue is a thread-safe queue whose put waits while it is full and whose take waits while it is empty. It does all the wait and notify work for you.
A BlockingQueue is the standard producer-consumer answer. This program passes five orders through a queue of two slots and stops the consumer with a poison pill.
Example 4 · Producer-consumer with ArrayBlockingQueue and a poison pill
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class BlockingQueueDemo { static final int POISON = -1; // tells the consumer to stop
public static void main(String[] args) throws InterruptedException { BlockingQueue<Integer> orders = new ArrayBlockingQueue<>(2);
Thread seller = new Thread(() -> { try { for (int order = 101; order <= 105; order++) { orders.put(order); // waits while the queue is full } orders.put(POISON); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } });
int[] served = {0}; Thread packer = new Thread(() -> { try { while (true) { int order = orders.take(); // waits while the queue is empty if (order == POISON) break; System.out.println("served order " + order); served[0]++; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } });
seller.start(); packer.start(); seller.join(); packer.join(); System.out.println("total served: " + served[0]); }}served order 101 served order 102 served order 103 served order 104 served order 105 total served: 5
What this code does
- The queue holds at most 2 orders, so the seller's
putwaits whenever the packer falls behind, andtakewaits when the queue is empty. Nosynchronized,waitornotifyis needed. - The seller ends with
POISON(-1); the packer stops when it takes it, so both threads finish andjoinreturns.
ArrayBlockingQueue is bounded (fixed array); LinkedBlockingQueue is optionally bounded. A poison pill is a special value the producer puts after the last real item; when the consumer takes it, it leaves its loop. With several consumers, put one pill per consumer. offer and poll with a timeout are the non-blocking alternatives.
Order of execution
Order the producer-consumer
Put the steps of a clean producer-consumer in order.
Round 4: explain the memory diagram for a program
Memory diagram is a whiteboard sketch with the stack (one frame per method call, holding locals) on one side and the heap (objects) on the other, with an arrow from each reference to its object.
Walk through the program top to bottom and place every value. This one has a static field, a list on the heap, two Order objects, and a second method frame.
STACK (main thread) HEAPquantity: orders --+, sum = 5 ArrayList cart -> [ref0, ref1]main: cart ----+--> ArrayList ref0 -> Order{item -> "laptop", qty 2} q = 5 ref1 -> Order{item -> "mouse", qty 3}MemoryDiagramDemo.class: totalOrders = 2 (static, one copy)Example 5 · The program behind the memory diagram
import java.util.ArrayList;import java.util.List;
public class MemoryDiagramDemo { static int totalOrders = 0;
static class Order { final String item; final int qty;
Order(String item, int qty) { this.item = item; this.qty = qty; totalOrders++; } }
static int quantity(List<Order> orders) { int sum = 0; for (Order o : orders) sum += o.qty; return sum; }
public static void main(String[] args) { List<Order> cart = new ArrayList<>(); // reference on main's stack cart.add(new Order("laptop", 2)); cart.add(new Order("mouse", 3)); int q = quantity(cart); System.out.println("items: " + q + ", orders created: " + totalOrders); }}items: 5, orders created: 2
What this code does
- Use this program with the diagram above: static
totalOrderslives once with the class,cartandqlive inmain's frame, and the list and orders are heap objects. quantityreceives a copy of the reference, so it reads the same list without copying it; its localsumdisappears when it returns.
Place the values: totalOrders is static, one copy with the class. In main's frame: the reference cart and the int q. On the heap: the ArrayList, its internal array, the two Order objects and the strings "laptop" and "mouse" (pooled literals). While quantity runs, a second frame sits above main with its own copies: the reference orders (pointing to the same list) and sum.
Finish with what happens next: when quantity returns, its frame is popped; when main ends, nothing references the list or orders, so they become eligible for GC.
Predict the output
Predict the memory trace
Read the code, then pick what it prints.
Round 1 of 2
A method changes a field of an object and a copy of an int.
Next step
Check your understanding
12 quick questions