Entrance Exams
Govt. Exams
AtomicInteger uses lock-free CAS operations which are more efficient than synchronized blocks or locks for simple counter operations with multiple threads.
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.
Once a thread completes (reaches TERMINATED state), calling start() again throws IllegalThreadStateException. A thread can only be started once.
Java thread states are: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED. SUSPENDED is not a valid state in Java's threading model.