Entrance Exams
Govt. Exams
interrupt() sets an internal interrupt flag. The thread must check this flag using isInterrupted() or interrupted() and handle it appropriately.
A Semaphore maintains a count allowing multiple threads (based on permit count) to access a resource. A Mutex (binary semaphore with count=1) allows only one thread.
notifyAll() wakes up all threads waiting on the monitor. They will then compete to acquire the lock when it's released.
wait() releases the monitor lock and causes the thread to wait until notify() or notifyAll() is called by another thread, enabling inter-thread communication.
CountDownLatch is a one-time use synchronizer. Once the count reaches zero, it cannot be reset. CyclicBarrier is reusable.
CyclicBarrier allows a set of threads to wait for each other to reach a common point, then all proceed together. It's reusable unlike CountDownLatch.
volatile int counter = 0;
counter++; // in multiple threads
Which issue may occur?
volatile only ensures visibility, not atomicity. counter++ is actually three operations (read, increment, write), so even with volatile, race conditions can occur.
volatile ensures that all threads see the most recent value of a variable (visibility) but does not provide atomicity for compound operations.
Virtual threads (Project Loom) are extremely lightweight and allow creating millions of threads efficiently, unlike platform threads which are limited by OS resources.
The synchronized keyword creates a critical section that only one thread can access at a time, preventing race conditions. volatile ensures visibility but not atomicity.