☕ Java
Intermediate
What is deadlock in Java?
Answer
A deadlock occurs when two or more threads are each waiting for a lock held by the other, creating a circular dependency that causes all involved threads to wait forever. Example: Thread A holds Lock 1 and waits for Lock 2; Thread B holds Lock 2 and waits for Lock 1 — neither can proceed. Four conditions are necessary for deadlock (Coffman conditions): mutual exclusion, hold and wait, no preemption, and circular wait. Prevention strategies include: always acquiring locks in a consistent order, using tryLock() with a timeout, or using higher-level concurrency utilities like java.util.concurrent that handle locking internally. Detect deadlocks using thread dumps or tools like VisualVM.
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?