1、死锁
final Object left = new Object();
final Object right = new Object();
public void doLeftRight() {
synchronized (left) {
synchronized (right) {
execute1();
}
}
}
public void doRightLeft() {
synchronized (right) {
synchronized (left) {
execute2();
}
}
}
private void execute2() {
}
private void execute1() {
}
}
JVM在解决死锁方面没有数据库那样强大,无法自动检测和处理死锁。往往只能通过中止并重启才能彻底恢复。
1)顺序死锁
public
class
LeftRightDeadLock {
final Object left = new Object();
final Object right = new Object();
public void doLeftRight() {
synchronized (left) {
synchronized (right) {
execute1();
}
}
}
public void doRightLeft() {
synchronized (right) {
synchronized (left) {
execute2();
}
}
}
private void execute2() {
}
private void execute1() {
}
}
2)动态锁顺序死锁
看似无害的代码,例如将资金从账户A转移到账户B,实际上在出现并发的逆操作时(从账户B转到账户A),就可能会出现死锁。
public
void
transferMoney(Account fromAccount,
//
Account toAccount,
//
int amount
) {
synchronized (fromAccount) {
synchronized (toAccount) {
fromAccount.decr(amount);
toAccount.add(amount);
}
}
}
int amount
) {
synchronized (fromAccount) {
synchronized (toAccount) {
fromAccount.decr(amount);
toAccount.add(amount);
}
}
}
处理这种情况的办法是通过锁顺序来避免
public class InduceLockOrder {
private static final Object tieLock = new Object();
public void transferMoney(final Account fromAcct,
final Account toAcct,
final DollarAmount amount)
throws InsufficientFundsException {
class Helper {
public void transfer() throws InsufficientFundsException {
if (fromAcct.getBalance().compareTo(amount) < 0)
throw new InsufficientFundsException();
else {
fromAcct.debit(amount);
toAcct.credit(amount);
}
}
}
int fromHash = System.identityHashCode(fromAcct);
int toHash = System.identityHashCode(toAcct);
if (fromHash < toHash) {
synchronized (fromAcct) {
synchronized (toAcct) {
new Helper().transfer();
}
}
} else if (fromHash > toHash) {
synchronized (toAcct) {
synchronized (fromAcct) {
new Helper().transfer();
}
}
} else {
synchronized (tieLock) {
synchronized (fromAcct) {
synchronized (toAcct) {
new Helper().transfer();
}
}
}
}
}
interface DollarAmount extends Comparable<DollarAmount> {
}
interface Account {
void debit(DollarAmount d);
void credit(DollarAmount d);
DollarAmount getBalance();
int getAcctNo();
}
class InsufficientFundsException extends Exception {
}
}