Entrance Exams
Govt. Exams
Virtual Threads (Project Loom, stable in Java 21+) allow massive parallelism with lightweight threads, reducing contention overhead. They enable better scaling than increasing pool size. volatile doesn't help with synchronized block contention, and static conversion is inappropriate.
BlockingQueue's take() method blocks the calling thread until an element becomes available. This is safer and more efficient than busy-waiting. NoSuchElementException is thrown by non-blocking operations like remove().
CountDownLatch is designed for one-time barrier scenarios where threads wait for a countdown to reach zero. With an initial count of 5, it perfectly suits this use case. Semaphore is reusable, Phaser handles multiple phases, and Mutex is not a Java class.
The wait() method causes a thread to release all acquired locks and enter a waiting state until notify() or notifyAll() is called. sleep(), yield(), and join() do not release locks.
Virtual Threads are lightweight and can be created in large numbers (millions) with minimal memory footprint, unlike platform threads which are heavy OS-level constructs. This solves scalability issues in high-concurrency applications.
StampedLock provides optimistic reads that don't require acquiring a lock. If the data changes during an optimistic read, validation fails and a pessimistic lock can be acquired.
Thread t = new Thread(() -> { throw new RuntimeException("Error"); });
t.setUncaughtExceptionHandler((thread, ex) -> System.out.println("Caught"));
t.start();
The UncaughtExceptionHandler is invoked when an exception is thrown in a thread and not caught. It will print 'Caught' before the thread terminates.
ForkJoinPool uses a work-stealing algorithm where idle threads can 'steal' tasks from busy threads' queues, providing better load balancing for divide-and-conquer problems.
Livelock occurs when threads are not blocked but continuously change state in response to each other (like two people trying to pass each other), preventing progress. This differs from deadlock where threads are blocked.
ReentrantReadWriteLock allows multiple threads to acquire the read lock simultaneously, but only one thread can hold the write lock. This improves concurrency for read-heavy workloads.