Govt. Exams
Entrance Exams
AtomicInteger suffers from false sharing when multiple threads frequently update adjacent memory locations on the same CPU cache line. LongAdder uses striped updates across multiple cells, reducing contention. This is a 2024-25 performance optimization best practice for high-concurrency scenarios.
ThreadLocal values persist across task executions in the same thread. ThreadPools reuse threads, so previous ThreadLocal values remain unless explicitly removed. This can cause data leakage. Developers must call remove() to clean up.
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.