Govt Exams
Object lock = new Object();
synchronized(lock) {
synchronized(lock) {
System.out.println("Nested");
}
}
Java supports reentrant locks on synchronized blocks. The same thread can acquire the same lock multiple times. The lock is released only when the outermost synchronized block exits.
Java 21 introduced Virtual Threads as a lightweight threading model under Project Loom, allowing millions of concurrent tasks. This is more efficient than platform threads for high-concurrency scenarios.
Context switching is the OS mechanism of switching CPU execution between different threads, saving and restoring thread state.
ExecutorService manages a pool of threads, reusing them for multiple tasks, which reduces overhead and improves resource utilization.
Synchronized methods automatically acquire and release the monitor lock (intrinsic lock) associated with the object, ensuring thread safety.
The getState() method returns the Thread.State enum indicating whether a thread is NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED.
interrupt() sets the interrupt status flag. If the thread is not waiting or sleeping, it continues execution but the status is marked as interrupted.
ConcurrentHashMap is designed for concurrent access and is thread-safe. ArrayList, HashMap, and TreeMap require external synchronization for thread safety.
When threads wait indefinitely for each other to release resources, it's a deadlock. This scenario is a classic deadlock example.
java
class Test extends Thread {
public void run() {
System.out.print("T");
}
}
public class Main {
public static void main(String[] args) {
Test t = new Test();
t.run();
t.start();
}
}
First t.run() executes directly (prints T), then t.start() creates a new thread and calls run() again (prints T). So output is TT.