Which of the following is a thread-safe collection in Java that can be used without explicit synchronization?
AArrayList
BHashMap
CConcurrentHashMap
DTreeMap
Correct Answer:
C. ConcurrentHashMap
EXPLANATION
ConcurrentHashMap is designed for concurrent access and is thread-safe. ArrayList, HashMap, and TreeMap require external synchronization for thread safety.
Consider a scenario where Thread A acquires Lock1 and tries to acquire Lock2, while Thread B acquires Lock2 and tries to acquire Lock1. What situation arises?
AThread starvation
BDeadlock
CLivelock
DRace condition
Correct Answer:
B. Deadlock
EXPLANATION
When threads wait indefinitely for each other to release resources, it's a deadlock. This scenario is a classic deadlock example.
What will be the output of the following code snippet?
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();
}
}
ATT
BT
CCompilation error
DRuntime exception
Correct Answer:
A. TT
EXPLANATION
First t.run() executes directly (prints T), then t.start() creates a new thread and calls run() again (prints T). So output is TT.
In Java multithreading, which method is used to pause the execution of a thread for a specified number of milliseconds without releasing locks?
AThread.sleep()
BThread.pause()
CThread.halt()
DThread.suspend()
Correct Answer:
A. Thread.sleep()
EXPLANATION
Thread.sleep() pauses thread execution for specified milliseconds while retaining all locks. pause(), halt(), and suspend() are not standard Java methods for this purpose.