BAEL-855 stm (#1855)

* BAEL-855 code for the STM article

* BAEL-855 method ordering

* BAEL-855 Better test case

* BAEL-855 formatting

* BAEL-855 rename

* BAEL-855 change to expected

* Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-855_stm

# Conflicts:
#	libraries/pom.xml
This commit is contained in:
Tomasz Lelek
2017-05-16 16:53:47 +02:00
committed by pedja4
parent ee79ac3a02
commit ce43d80f8b
3 changed files with 213 additions and 15 deletions
@@ -0,0 +1,50 @@
package com.baeldung.stm;
import org.multiverse.api.StmUtils;
import org.multiverse.api.callables.TxnCallable;
import org.multiverse.api.references.TxnInteger;
import org.multiverse.api.references.TxnLong;
public class Account {
private final TxnLong lastUpdate;
private final TxnInteger balance;
public Account(final int balance) {
this.lastUpdate = StmUtils.newTxnLong(System.currentTimeMillis());
this.balance = StmUtils.newTxnInteger(balance);
}
public Integer getBalance() {
return balance.atomicGet();
}
public void adjustBy(final int amount) {
adjustBy(amount, System.currentTimeMillis());
}
public void adjustBy(final int amount, final long date) {
StmUtils.atomic(() -> {
balance.increment(amount);
lastUpdate.set(date);
if (balance.get() < 0) {
throw new IllegalArgumentException("Not enough money");
}
});
}
public void transferTo(final Account other, final int amount) {
StmUtils.atomic(() -> {
final long date = System.currentTimeMillis();
adjustBy(-amount, date);
other.adjustBy(amount, date);
});
}
@Override
public String toString() {
return StmUtils.atomic((TxnCallable<String>)
txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn));
}
}