Java Concurrency

Threads, synchronized and locks, wait/notify, executors and thread pools, Future and CompletableFuture, atomics, concurrent collections, synchronizers (CountDownLatch, Semaphore), and common bugs.

Advanced 4 min readLesson 12 of 14 Interview Q&A

Java has had threads since 1.0 and a rich concurrency library (java.util.concurrent) since Java 5. This lesson is the practical toolkit; the why behind visibility and ordering is in Java memory model, and the general theory in Synchronization.

Threads

Java
Thread t = new Thread(() -> System.out.println("hi from " + Thread.currentThread().getName()));
t.start();          // NOT run(): run() executes on the current thread
t.join();           // wait for it to finish

Thread v = Thread.ofVirtual().start(() -> work());    // Java 21 virtual thread

Thread states: NEW → RUNNABLE → (BLOCKED on a monitor / WAITING / TIMED_WAITING) → TERMINATED. In real code you rarely create threads directly — use executors.

The problem: race conditions

Java
class Counter {
    private int count = 0;
    void increment() { count++; }    // read, add, write: three steps, not atomic
}
// Two threads × 1,000,000 increments → often prints far less than 2,000,000

synchronized

Every object has an intrinsic monitor lock. synchronized gives mutual exclusion and visibility (changes made inside are seen by the next thread to acquire the same lock).

Java
class Counter {
    private int count = 0;
    public synchronized void increment() { count++; }          // locks 'this'
    public synchronized int get() { return count; }             // reads need the lock too!
}

// Synchronized block: lock a private object, keep the critical section small
private final Object lock = new Object();
void add(Item i) {
    var processed = expensiveTransform(i);     // outside the lock
    synchronized (lock) { items.add(processed); }
}

Monitors are reentrant: a thread holding a lock can acquire it again (so synchronized methods can call each other).

wait / notify

Low-level condition waiting on a monitor — always in a loop (spurious wake-ups, and the condition may have changed):

Java
synchronized (lock) {
    while (queue.isEmpty()) lock.wait();      // releases the lock while waiting
    return queue.poll();
}
// producer
synchronized (lock) { queue.add(x); lock.notifyAll(); }

Prefer higher-level tools (BlockingQueue, Condition, latches) — they're easier to get right.

Explicit locks

java.util.concurrent.locks offers more control than synchronized:

Java
private final ReentrantLock lock = new ReentrantLock();
private final Condition notEmpty = lock.newCondition();

void put(T x) {
    lock.lock();
    try { queue.add(x); notEmpty.signal(); }
    finally { lock.unlock(); }                 // ALWAYS in finally
}

boolean tryTransfer() throws InterruptedException {
    if (lock.tryLock(100, TimeUnit.MILLISECONDS)) {   // timeout: avoids deadlock
        try { ...; return true; } finally { lock.unlock(); }
    }
    return false;
}
synchronizedReentrantLockReadWriteLockStampedLock
Timeout / tryLockNoYesYesYes
Interruptible waitNolockInterruptiblyYesYes
Multiple conditionsOne per monitorManyYes—
Many readers at onceNoNoYesYes, plus optimistic reads
ReleaseAutomaticManual (finally)ManualManual

Executors and thread pools

Creating a thread per task is expensive (for platform threads) and unbounded. An executor reuses a pool of worker threads fed by a task queue.

submit(task)Task queuebounded!worker 1worker 2worker N
Java
ExecutorService pool = Executors.newFixedThreadPool(8);
Future<Integer> f = pool.submit(() -> compute());      // Callable returns a value
Integer result = f.get(2, TimeUnit.SECONDS);           // blocks; throws TimeoutException

List<Future<String>> all = pool.invokeAll(tasks);      // run many, wait for all

pool.shutdown();                                       // stop accepting, finish queued tasks
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) pool.shutdownNow();   // interrupt stragglers

// Java 19+: ExecutorService is AutoCloseable
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) { ... }

Sizing: CPU-bound work ≈ number of cores. I/O-bound work ≈ cores × (1 + wait time / compute time) — or use virtual threads.

CompletableFuture: composing async work

Java
CompletableFuture<User> userF = CompletableFuture.supplyAsync(() -> userService.load(id), ioPool);
CompletableFuture<List<Order>> ordersF = CompletableFuture.supplyAsync(() -> orderService.forUser(id), ioPool);

CompletableFuture<Dashboard> dash = userF
        .thenCombine(ordersF, Dashboard::new)                  // run both in parallel, combine
        .thenApply(Dashboard::withRecommendations)             // transform
        .orTimeout(2, TimeUnit.SECONDS)
        .exceptionally(ex -> Dashboard.fallback());            // recover

CompletableFuture.allOf(f1, f2, f3).join();                    // wait for all
CompletableFuture.anyOf(primary, replica).join();              // first to complete
MethodLike
thenApplymap
thenComposeflatMap (the function returns another future)
thenCombineZip two futures
thenAccept / thenRunConsume / side effect
exceptionally / handle / whenCompleteError handling

Always pass your own executor for blocking work — the default (ForkJoinPool.commonPool()) is shared and sized for CPU work.

Atomics and adders

Lock-free updates using CPU compare-and-swap (CAS):

Java
AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();
counter.updateAndGet(x -> Math.max(x, observed));
counter.compareAndSet(expected, newValue);

LongAdder hits = new LongAdder();     // far faster than AtomicLong under heavy contention:
hits.increment();                     // spreads updates across cells, sums on read
long total = hits.sum();

AtomicReference<Config> config = new AtomicReference<>(initial);
config.set(reloaded);                 // safe publication of an immutable object

Synchronizers

ToolPurposeExample
CountDownLatchWait until N events happen (one-shot)Main thread waits for 5 services to start
CyclicBarrierN threads wait for each other, repeatedlyPhased simulations
SemaphoreLimit concurrent access to N permitsAt most 10 concurrent calls to an API
PhaserFlexible, dynamic barrierMulti-phase tasks with changing parties
ExchangerTwo threads swap objectsPipelined buffers
Java
Semaphore permits = new Semaphore(10);
permits.acquire();
try { callRateLimitedApi(); } finally { permits.release(); }

CountDownLatch ready = new CountDownLatch(3);
for (var s : services) pool.submit(() -> { s.start(); ready.countDown(); });
ready.await(30, TimeUnit.SECONDS);

Concurrent collections

ConcurrentHashMap (with atomic compute, merge, computeIfAbsent), CopyOnWriteArrayList, BlockingQueue implementations (ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue), ConcurrentSkipListMap. See Collections.

Interruption

Java threads are stopped cooperatively. thread.interrupt() sets a flag; blocking methods (sleep, wait, take, join) throw InterruptedException. Long-running loops should check Thread.currentThread().isInterrupted(). Never swallow InterruptedException — rethrow it or restore the flag with Thread.currentThread().interrupt().

Common bugs

BugCauseFix
Race conditionUnsynchronised read-modify-writeLocks, atomics, confinement, immutability
DeadlockTwo threads take two locks in opposite orderGlobal lock order, tryLock with timeout (Deadlocks)
Visibility bugOne thread never sees another's writevolatile, locks, atomics (JMM)
Thread starvation / pool deadlockTasks in a pool block waiting for other tasks in the same full poolSeparate pools; don't block in pool threads
Lost exceptionsException in submit()ed task sits unseen in the FutureCall get(), or handle inside the task
ThreadLocal leaksValues persist in pooled threadsremove() in finally
Key takeaways
  • Use executors, not raw threads; bound queues and pool sizes in production.
  • synchronized and locks give mutual exclusion plus visibility; always unlock in finally.
  • CompletableFuture composes async tasks: thenApply, thenCompose, thenCombine, exceptionally.
  • Atomics and LongAdder for lock-free counters; ConcurrentHashMap's compute methods for atomic updates.
  • Latches, semaphores and barriers coordinate threads; interruption is cooperative.
Interview questions
QHow would you make a counter thread-safe? Compare the options.medium

synchronized methods (simple, correct, but contended threads block), AtomicInteger (lock-free CAS, good under moderate contention), LongAdder (striped cells, best under heavy write contention, slightly costlier reads), or confining the counter to one thread. volatile alone is not enough because count++ is a read-modify-write.

QWhat is the difference between submit() and execute()?easy

execute(Runnable) runs a task with no result; an uncaught exception goes to the thread's uncaught exception handler. submit() accepts Runnable or Callable and returns a Future; exceptions are captured in the Future and only surface when you call get(), so they're easily lost if nobody checks.