Concurrency and Multithreading
Domain 6 tests thread lifecycle, safe publication, and the java.util.concurrent toolkit: how to start work, how to stop it cleanly, and which classes remove the need for hand-written synchronization.
Threads
- Create with
ThreadorRunnable;start()launches a new thread, whilerun()merely executes on the current thread. - States: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED.
join()waits for termination;interrupt()sets the interrupt flag and wakes blocking calls withInterruptedException. Callable<V>returns a value and may throw checked exceptions;Runnablecannot.
Memory and safety
synchronizedgives mutual exclusion plus visibility;volatilegives visibility and ordering but not atomicity, socount++remains unsafe.AtomicInteger,LongAdderandjava.util.concurrent.lockscover common cases withoutsynchronizedblocks.- Immutable objects are inherently thread-safe; safely publish any shared mutable state.
Executors and concurrent collections
Executors.newFixedThreadPool,newSingleThreadExecutor,newCachedThreadPool; always shut down withshutdown()(graceful) orshutdownNow()(interrupts running tasks).Future.get()blocks and throwsExecutionExceptionwrapping the task's own exception;CompletableFuturecomposes asynchronous stages.ConcurrentHashMapsupports concurrent reads and updates and rejects null;CopyOnWriteArrayListsuits read-heavy lists.
Worked example
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Integer> f = pool.submit(() -> 1 / 0);
try { f.get(); }
catch (ExecutionException e) { System.out.println(e.getCause()); } // ArithmeticException
finally { pool.shutdown(); }
The division error is captured inside the Future; get() rethrows it wrapped in ExecutionException.
Traps
- Deadlock arises when two threads acquire the same locks in opposite orders; consistent lock ordering prevents it.
wait,notifyandnotifyAllrequire holding the monitor;await/signalbelong toCondition.- A terminated thread cannot be restarted.