Govt. Exams
Entrance Exams
CountDownLatch is used for one-time synchronization where threads wait for a countdown to reach zero. CyclicBarrier can be reused after threads are released.
CyclicBarrier allows multiple threads to wait for each other at a specific point. CountDownLatch is for one-time synchronization; CyclicBarrier is reusable.
java
synchronized void method1() { method2(); }
synchronized void method2() { }
Java's intrinsic locks are reentrant, meaning the same thread can acquire the same lock multiple times. The thread can call method2() from method1() without deadlock.
This is a classic circular wait scenario resulting in deadlock, where neither thread can proceed because each is waiting for a resource held by the other.
Semaphore is a synchronization utility that uses a counter to control access to a shared resource. Threads can acquire and release permits.
When sleep() is called inside a synchronized block, the thread retains the lock on the object, preventing other threads from entering the synchronized section.
The volatile keyword ensures that changes to a variable are immediately visible to all threads, providing memory visibility without the overhead of full synchronization.
wait() must be called from within a synchronized context. Calling it without holding the lock throws IllegalMonitorStateException.