Middle — Middle+
How can a deadlock state be artificially induced in a system?
sobes.tech AI
Answer from AI
In Android (and generally in multithreaded systems), a deadlock occurs when two or more threads are permanently waiting for resources held by each other.
You can artificially induce a deadlock if two threads acquire two resources in different orders. For example:
final Object resource1 = new Object();
final Object resource2 = new Object();
Thread t1 = new Thread(() -> {
synchronized (resource1) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (resource2) {
// work with resources
}
}
});
Thread t2 = new Thread(() -> {
synchronized (resource2) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (resource1) {
// work with resources
}
}
});
t1.start();
t2.start();
Here, t1 acquires resource1, then tries to acquire resource2, while t2 does the opposite — first resource2, then resource1. If both threads manage to acquire their first resource before the other releases it, they will be blocked forever, waiting for each other.
Thus, to artificially induce a deadlock, you need:
- At least two resources (monitors)
- Two threads that acquire these resources in different orders
- Add delays to increase the chance of simultaneous acquisition
This is a classic example of mutual locking.