简体   繁体   中英

Happen before relationship to avaid deadlock

In some article i read if happen before relationship is maintained in a multithreading program in java, there is no chance of arising data race. But my doubt is will it help also to prevent deadlock situations too?

I feel it may help, but could not explain in a proper way. Could anybody explain deadlock in terms of happen-before relationship?

happens-before relationship (HBR) has little to do with deadlocks. HBR is required to correctly implement synchronization primitives. Deadlock avoidance is about correct usage of synchronization primitives. If primitives are implemented incorrectly, even correct usage can cause system to hang, which looks as if a deadlock occurred - this is the closest relation of HBR and deadlock I can imagine.

This code is properly synchronized and free of data races:

public void transfer(Account from, Account to, Amount amount) {
    synchronized(from) {
        synchronized(to) {
            from.debit(amount);
            to.credit(amount);
        }
    }
}

However it can easily deadlock if you call transfer(accountA, accountB); and transfer(accountB, accountA); concurrently.

It happens that the synchronized create hb relationships, but that does not come into play to decide if the code should deadlock or not.

For example, you could implement something very similar with Lock objects and avoid the deadlock with tryLock while keeping the exact same hb relationships as in the example above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM