您的位置:首页 > 其它

知识库--Creating Nested Transactions By Akka 内存嵌套事务(129)

2017-03-02 08:28 399 查看
public class Account {
final private Ref<Integer> balance = new Ref<Integer>();
public Account(int initialBalance) {
balance.swap(initialBalance);//自带事务
}
public int getBalance() {
return balance.get();//自带事务
}


存款操作必须在一个事务中完成

原因:涉及到账户的读和写操作

public void deposit(final int amount) {
new Atomic<Boolean>() {
public Boolean atomically() {
System.out.println("Deposit " + amount);
if (amount > 0) {
balance.swap(balance.get() + amount);//外层事务保证
return true;
}
throw new AccountOperationFailedException();
}
}.execute();
}


历史:使用锁进行事务化

public boolean transfer(
final Account from, final Account to, final int amount)
throws LockException, InterruptedException {
final Account[] accounts = new Account[] {from, to};
Arrays.sort(accounts);
if(accounts[0].monitor.tryLock(1, TimeUnit.SECONDS)) {
try {
if (accounts[1].monitor.tryLock(1, TimeUnit.SECONDS)) {
try {
if(from.withdraw(amount)) {
to.deposit(amount);
return true;
} else {
return false;
}
} finally {
accounts[1].monitor.unlock();
}
}
} finally {
accounts[0].monitor.unlock();
}
}
throw new LockException("Unable to acquire locks on the accounts");
}


now:使用STM–akka

public void transfer(
final Account from, final Account to, final int amount) {
new Atomic<Boolean>() {
public Boolean atomically() {
to.deposit(amount);
from.withdraw(amount);
return true;
}
}.execute();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  事务 内存 并发