Entrance Exams
Govt. Exams
int x = 10;
try {
x = x / 0;
} catch(ArithmeticException e) {
x = x + 5;
} finally {
x = x * 2;
}
System.out.println(x);
ArithmeticException is caught, x becomes 10+5=15. Finally block executes, x becomes 15*2=30. Finally block always executes regardless of exception.
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().
When a thread waiting at a CyclicBarrier is interrupted, it throws InterruptedException. This breaks the barrier and causes other waiting threads to receive BrokenBarrierException.
ExecutorService es = Executors.newFixedThreadPool(2);
es.execute(() -> System.out.println("Task 1"));
es.shutdown();
shutdown() gracefully shuts down the executor service by rejecting new tasks but allowing submitted tasks to complete. Task 1 is already submitted before shutdown(), so it will execute.
Java 21 introduced Virtual Threads as part of Project Loom, which are lightweight threads that make it easier to write scalable concurrent applications.
volatile ensures that changes to a variable are immediately visible to all threads and prevents the JVM from reordering instructions. However, it doesn't make operations atomic.
AtomicInteger and other Atomic* classes use CAS operations for lock-free thread-safe operations. ConcurrentHashMap uses segment-based locking, not CAS.
yield() is a hint to the thread scheduler that the current thread is willing to yield its current use of CPU. It doesn't guarantee the thread will yield, as scheduling is JVM-dependent.
synchronized void method1() { wait(); }
If wait() is called without a lock, what happens?
wait() must be called from within a synchronized block or method. If called outside synchronized context, it throws IllegalMonitorStateException at runtime.