V6129. Possible deadlock due to incorrect synchronization order between locks.
The analyzer has detected a potential deadlock caused by a violation of the lock acquisition order across different methods. This happens when synchronized code blocks acquire object monitors in inconsistent sequences. When such methods run concurrently, two threads may wait indefinitely for each other while holding different locks.
The example:
void foo() {
synchronized (lock1) {
synchronized (lock2) {
....
}
}
}
void bar() {
synchronized (lock2) {
synchronized (lock1) {
....
}
}
}
If one thread starts executing foo()
and acquires lock1
first, while another thread concurrently runs bar()
and acquires lock2
, the first thread will be blocked when attempting to acquire lock2
, and the second thread will be blocked while waiting for lock1
. A deadlock occurs because each thread is holding a resource that the other one needs, causing both to wait indefinitely unless externally interrupted.
The fixed code:
void foo() {
synchronized (lock1) {
synchronized (lock2) {
....
}
}
}
void bar() {
synchronized (lock1) {
synchronized (lock2) {
....
}
}
}
This diagnostic is classified as:
|