Junior — Middle
What methods can be used to eliminate or prevent deadlocks in a system?
sobes.tech AI
Answer from AI
To prevent deadlocks in Java, several approaches can be used:
- Avoid nested locks: minimize the number of locks held simultaneously.
- Order resource acquisition: always acquire locks in the same order.
- Use timeouts: apply methods with timeouts (e.g., tryLock with timeout) to avoid infinite waiting.
- Avoid locking when possible: use non-blocking data structures or atomic operations.
Example of lock acquisition ordering:
synchronized(lock1) {
synchronized(lock2) {
// work with resources
}
}
Always acquire lock1 before lock2 to prevent cyclic waiting.