Entrance Exams
Govt. Exams
Calling interrupt() on a blocked thread sets the interrupt flag. If the blocking operation supports interruption (like sleep(), join(), wait()), it throws InterruptedException. Non-interruptible I/O blocks require other mechanisms.
ForkJoinPool is designed for divide-and-conquer tasks where large problems are split (fork) into smaller subtasks and results are combined (join). It's optimized for recursive parallel algorithms.
Safe publication requires using visibility mechanisms: synchronized (mutual exclusion), volatile (visibility), or thread-safe collections (both). Direct assignment without synchronization causes visibility issues in the memory model.
Java guarantees that the lock is released when exiting a synchronized block, whether normally or via an exception. This is why synchronized is considered safer than manual lock management.
Virtual Threads are lightweight (millions can run) with minimal memory overhead compared to platform threads (thousands). They automatically handle I/O blocking without thread creation, making them ideal for high-concurrency scenarios.
ReentrantLock provides more control with tryLock() for non-blocking attempts, Condition objects for complex wait/notify patterns, and fairness policy. It's more flexible than synchronized.
Thread.stop() is deprecated and unsafe. Modern approaches use either a volatile flag or Thread.interrupt() with proper handling. Both are valid and recommended depending on the scenario.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> System.out.println("Task 1"));
executor.submit(() -> System.out.println("Task 2"));
executor.shutdown();
newSingleThreadExecutor() creates an executor with exactly one thread. Tasks are queued and executed sequentially in the order submitted. Task 1 will always execute before Task 2.
This is a classic deadlock scenario involving circular wait. Race condition involves competing for resources. Starvation is when a thread never gets the resource. Livelock is when threads keep changing states without progress.
ConcurrentHashMap uses segment-based locking (in older versions) or fine-grained locking to provide thread-safety without synchronizing the entire map. Other options require external synchronization or Collections.synchronizedMap().