Junior — Middle
How can mutual blocking of two threads in a multithreaded application be prevented?
sobes.tech AI
Answer from AI
Mutual blocking (deadlock) occurs when two or more threads are forever waiting for resources held by each other. To prevent deadlock, the following approaches can be used:
- Avoid nested locks: minimize the number of resources locked simultaneously.
- Order resource acquisition: always acquire resources in the same order across all threads.
- Use timeouts: attempt to acquire locks with a timeout to avoid infinite waiting.
- Use higher-level synchronization primitives: for example, the
java.util.concurrentpackage in Android, which reduces the likelihood of deadlock.
Example of ordered resource acquisition:
synchronized (resourceA) {
synchronized (resourceB) {
// work with resources
}
}
If all threads follow the order of first resourceA, then resourceB, deadlock will not occur.