CIP - avoid liveness hazards

    We use lock to ensure thread safety, but indiscriminate use of locking can cause lock-ordering deadlocks.

    

# deadly embrace

When thread A holds lock L and try to acquire lock M, but at the same time thread B holds lock M and try to acquire lock L, both threads will wait forever.


# lock-ordering deadlock

This problem come about when two threads attempt to acquire the same locks in different order.

A program will be free of lock-ordering deadlocks if all threads acquire the locks they need in a fixed order.

/** code sample for lock-ordering deadlock */
public class LeftRightlock {
	
	private final Object left = new Object();
	private final Object right = new Object();
	
	public void leftRight() {
		synchronized (left) {
			synchronized (right) {
				// ...
			}
		}
	}
	
	public void rightLeft() {
		synchronized (right) {
			synchronized (left) {
				// ...
			}
		}
	}
}


# dynamic lock order deadlock

in fact, the lock order depends on the order of arguments passed to the method:

public void transferMoney(final Account fromAcct, 
                          final Account toAcct, 
                          final double amount) throws Exception {
    synchronized (fromAcct) {
        synchronized (toAcct) {
            if (fromAcct.getBalance() < amount) {
                throw new Exception("insufficient balance");
            } else {
                fromAcct.debitt(amount);
                toAcct.credit(amount);
            }
        }
    }
}

to solve the above problem, we can use System.identityHashCode(obj) to decide the order.


# Avoid deadlock

One technique for detecting and recovering from deadlocks is to use timed tryLock of the explicit lock instead of intrinsic locking.


#starvation

Startvation occurs when a thread perpetually denied access to resources it needs.

Starvation can be caused by inappropriate use of thread priorities.


# priority

The thread API defines 10 priority levels that JVM can map to OS scheduling priorities, this mapping is platform-specific. Some different java priorities can map to same OS priority.


# livelock

Livelock is also a form of liveness failure in which a thread, while not blocked, still cannot make progress because it keeps retrying an operation that will always fail.

The solution for livelock is to introduce some randomness into retry mechanism.





转载于:https://my.oschina.net/u/1242229/blog/285818

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值