Best way to avoid deadlock for several objects transaction? - java

I was looking for deadlock example and stumbled across this code:
package com.example.thread.deadlock._synchronized;
public class BankAccount {
double balance;
int id;
BankAccount(int id, double balance) {
this.id = id;
this.balance = balance;
}
void withdraw(double amount) {
// Wait to simulate io like database access ...
try {Thread.sleep(10l);} catch (InterruptedException e) {}
balance -= amount;
}
void deposit(double amount) {
// Wait to simulate io like database access ...
try {Thread.sleep(10l);} catch (InterruptedException e) {}
balance += amount;
}
static void transfer(BankAccount from, BankAccount to, double amount) {
synchronized(from) {
from.withdraw(amount);
synchronized(to) {
to.deposit(amount);
}
}
}
public static void main(String[] args) {
final BankAccount fooAccount = new BankAccount(1, 100d);
final BankAccount barAccount = new BankAccount(2, 100d);
new Thread() {
public void run() {
BankAccount.transfer(fooAccount, barAccount, 10d);
}
}.start();
new Thread() {
public void run() {
BankAccount.transfer(barAccount, fooAccount, 10d);
}
}.start();
}
}
How would you change transfer method so that it doesn't cause deadlock? First thought is to create a shared lock for all accounts, but that of course would just kill all concurrency. So is there a good way to lock just two accounts involved into a transaction and not affect other accounts?

One way to avoid deadlocks in multi-lock situations is to always lock the objects in the same order.
In this case it would mean that you'd create a total ordering for all BankAccount objects. Luckily we've got an id that we can use, so you could always lock the lower id first and then (inside the other synchronized block) the higher id one.
This assumes that there's no BankAccount objects with identical ids, but that seems like a reasonable assumption.

Use two synchronized blocks separately instead of nested.
synchronized(from){
from.withdraw(amount);
}
synchronized(to){
to.deposit(amount);
}
So after from.withdraw(amount) is called, the lock on from is released before it tries to lock on to

Related

Java Concurrency - Wrong Result When Using Synchronized Keyword

I am sorry for this basic question but I am so curious why I am not getting the correct result for the below code. I have a basic Account class which has 3 non-synchronized and 3 synchronized methods that do the same jobs. My expectation is to calculate the correct result when I use the synchronized keyword but when i run the application unfortunately I am getting a wrong error. What I am missing here? Thanks in advance guys!
Here's the Account class
public class Account {
private double balance;
public Account(int balance) {
this.balance = balance;
}
public boolean rawWithDraw(int amount) {
if (balance >= balance) {
balance = balance - amount;
return true;
}
return false;
}
public void rawDeposit(int amount) {
balance = balance + amount;
}
public double getRawBalance() {
return balance;
}
public boolean safeWithDraw(final int amount) {
synchronized (this){
if (balance >= amount) {
balance = balance - amount;
return true;
}
}
return false;
}
public void safeDeposit(final int amount) {
synchronized (this) {
balance = balance + amount;
}
}
public double getSafeBalance() {
synchronized (this) {
return balance;
}
}
}
and here's the main application
public class Main {
public static void main(String[] args) {
Account account1 = new Account(0);
Thread tA = new Thread(() -> account1.safeDeposit(70));
Thread tB = new Thread(() -> account1.safeDeposit(50));
tA.setName("thread-A");
tB.setName("thread-B");
tA.start();
tB.start();
System.out.println("The balance is : " + account1.getRawBalance());
}
}
And when I run the code, sometimes it prints 70, sometimes 0 and sometimes 120. What causing this?
You have not included getRawBalance() as a synchronized method, so it is allowed to run concurrently with either of the two synchronized methods. You can therefore see the result before either method executes, after both methods execute, or in between one and the other, giving four different possible outcomes.

In this multithreaded java application only one thread seems to be running like a sequential program?

Sorry for lengthy description. If it's too long please tell me how to improve.
I am learning about Java concurrency. This is a scenario I tried to code.
A mother and a child share a bank account. Mother and child are two separate threads and are started from the main thread of the program.
In the run() of both, they perform several bank transactions. For simplicity, the child does only withdraw transactions and mother does only deposit transactions. Each transaction is also a separate thread. Child/Mother have to wait until one transaction is complete to start the next. (wait/notifyAll used for this).
If a withdrawal task tries to withdraw but there is an insufficient balance (balance is 0 initially) then the thread goes to a while loop waiting till the balance becomes greater than withdrawal amount.
Mother sleeps 500ms between each deposit task.
What I expected
Since the mother sleeps between every deposit and the child doesn't sleep during withdrawals it is guaranteed that the child's tasks will enter the insufficient funds while loop. However, since the mother is a separate thread, after waiting 500ms it will deposit some money. Then the child's withdrawal task thread will notice this, get out of the while loop and complete the transaction.
What happens
Child goes to a infinite loop trying to withdraw. Mother's thread does not deposit.
I have a hunch that this is something to do with wait(). When I call task.wait() from child, it is waiting for this specific instance of Task class to call notify() right? Not all instances of Task class.
public class Test {
public static void main(String[] args) {
Account account = new Account();
new Child("Bob", account).start();
new Mother("mary", account).start();
}
}
class Child extends Thread {
String name;
Account account;
public Child(String name, Account account) {
super("Child");
this.name = name;
this.account = account;
}
private void transaction(int val, TaskType taskType) {
Task task = new Task(account, taskType, val);
task.start();
synchronized (task) {
try {
task.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void run() {
this.transaction(100, TaskType.WITHDRAW);
System.out.println("100 WITHDRAW");
this.transaction(150, TaskType.WITHDRAW);
System.out.println("150 WITHDRAW");
this.transaction(200, TaskType.WITHDRAW);
System.out.println("200 WITHDRAW");
this.transaction(500, TaskType.WITHDRAW);
System.out.println("500 WITHDRAW");
}
}
class Mother extends Thread {
String name;
Account account;
public Mother(String name, Account account) {
super("Mother");
this.name = name;
this.account = account;
}
private void transaction(int val, TaskType taskType) {
Task task = new Task(account, taskType, val);
task.start();
synchronized (task) {
try {
task.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void run() {
this.transaction(100, TaskType.DEPOSIT);
System.out.println("100 DEPOSIT");
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.transaction(150, TaskType.DEPOSIT);
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("150 DEPOSIT");
this.transaction(200, TaskType.DEPOSIT);
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("200 DEPOSIT");
this.transaction(500, TaskType.DEPOSIT);
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("500 DEPOSIT");
}
}
class Task extends Thread {
private static int id = 0;
Account account;
TaskType taskType;
int val;
public Task(Account account, TaskType taskType, int val) {
super("Task");
this.account = account;
this.taskType = taskType;
this.val = val;
}
#Override
public void run() {
switch (taskType) {
case WITHDRAW:
account.withdraw(val, id);
break;
case DEPOSIT:
account.deposit(val, id);
break;
}
id += 1;
}
}
class Account {
int balance = 0;
public synchronized void deposit(int val, int id) {
this.balance += val;
this.notifyAll();
}
public synchronized void withdraw(int val, int id) {
while (this.balance < val) {
System.out.println("Funds insufficient waiting..." + id);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.balance -= val;
System.out.println("Withdrawal successful " + id);
this.notifyAll();
}
}
enum TaskType {
DEPOSIT,
WITHDRAW
}
Update - synchronized on account object instead of task
private void transaction(int val, TaskType taskType) {
Task task = new Task(account, taskType, val);
task.start();
synchronized (account) {
try {
account.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Did for both Mother and Child. I'm getting the same output.
The Mother and Child threads are waiting on the same task object, so they will wake up if you call task.notifyAll(). However, that's not what's happening. It is the account that calls notifyAll when more money is deposited.
The main problem with this implementation is that task is a separate thread. If you still want to keep it that way, then this is what you can do:
First: Account.withdraw waits with a Sleep. Instead, it should use wait(), so when Account.deposit calls notifyAll, it can wake up.
Your Mother and Child threads can wait on task, but then task has to notify them. So at the end of Task.run you should call notifyAll to wake up any threads waiting on the task.
You are essentially using three threads to run a sequential task.

Java Threading - Solution to deadlock?

I have put together some Java code which demonstrates deadlock in threading. On it's own, I usually get 2 lines output and an exception, sometimes before and sometimes after the output lines which is expected. The exception I get is a NullPointerException on the first line of the transfer() method.
The problem I'm having is I'd like to know how to solve this deadlock problem. I have had a search on StackOverflow of this problem and found this page:
Avoid Deadlock example
As solutions, I have tried what Will Hartung and what Dreamcash posted but I still get exceptions when trying to use synchronize or a ReentrantLock object.
Here's the code:
Account class:
public class Account {
int id;
double balance;
public Account(int id, double balance){
this.id = id;
this.balance = balance;
}
public void withdraw(double amount){
balance = balance - amount;
}
public void deposit(double amount){
balance = balance + amount;
}
public int getID(){
return id;
}
public double getBalance(){
return balance;
}
}
Bank Class (a singleton):
public class Bank{
static Bank bank;
Account a1;
Account a2;
private Bank(){}
public static Bank getInstance(){
if(bank==null){
bank = new Bank();
bank.setAccountOne(new Account(1, 100));
bank.setAccountTwo(new Account(2, 100));
}
return bank;
}
public void transfer(Account from, Account to, double amount){
from.withdraw(amount);
to.deposit(amount);
}
public Account getAccountOne(){
return a1;
}
public Account getAccountTwo(){
return a2;
}
public void setAccountOne(Account acc){
a1 = acc;
}
public void setAccountTwo(Account acc){
a2 = acc;
}
}
PersonOne class:
public class PersonOne implements Runnable {
public void run() {
Bank bank = Bank.getInstance();
Account a1 = bank.getAccountOne();
Account a2 = bank.getAccountTwo();
bank.transfer(a2, a1, 10);
System.out.println("T1: New balance of A1 is " + a1.getBalance());
System.out.println("T1: New balance of A2 is " + a2.getBalance());
}
}
PersonTwo class:
public class PersonTwo implements Runnable {
public void run() {
Bank bank = Bank.getInstance();
Account a1 = bank.getAccountOne();
Account a2 = bank.getAccountTwo();
bank.transfer(a1, a2, 10);
System.out.println("T2: New balance of A1 is " + a1.getBalance());
System.out.println("T2: New balance of A2 is " + a2.getBalance());
}
}
And finally, my main method
public static void main(String[] args){
PersonOne p1 = new PersonOne();
PersonTwo p2 = new PersonTwo();
Thread t1 = new Thread(p1);
Thread t2 = new Thread(p2);
t1.start();
t2.start();
}
The exception I get is a NullPointerException on the first line of the transfer() method.
The problem I'm having is I'd like to know how to solve this deadlock problem.
Your code cannot possible provoke any deadlocks. What it does provoke is write visibility issues: one of the threads gets to invoke the lazy Bank initializer and the other thread does not see the write.
To get deadlocks you first need any kind of locking (the synchronized keyword). Your particular NPE problem will be solved by adding synchronized to the getInstance method and it will not introduce any deadlocks.
My conclusion is that your best recourse is reading some introductory material on concurrency in Java.
There is a number of solutions and some of the less obvious ones are
use one thread and don't use locks. In this example, the code will me much simpler and much faster with just one thread as the overhead of locks exceeds the work being done.
as this is just an example, you cold use just one global lock. This will not perform as well as multiple locks but it is much simpler and if you don't need the performance you should do the simpler , less likely to get bugs. This cannot get a deadlock.
if you have to use multiple lock because this is homework, you can ensure you always lock in the same order. You can do this by sorting the objects on a unique key and always lock the "first" item first.
lastly, you can lock the objects in any order by use tryLock on the second account. If this fails, release both locks and try again. You can perform a tryLock on a monitor using Unsafe.tryMonitor().
Thanks for your answers.
I'm currently learning about threading. In the above, I was purposefully trying to create a deadlock, so that I could learn how to solve the problem of deadlocks (if I actually wanted a program that did the above, I would just avoid multi-threading).
The reason I used a singleton was so the two threads would be trying to use the same objects.
So... the above was the code I used to try to recreate a deadlock, so I was expecting problems/exceptions when running. One way I tried to then fix it was by rewriting the transfer method to look like this:
public void transfer(Account from, Account to, double amount){
synchronized(from){
synchronized(to){
from.withdraw(amount);
to.withdraw(amount);
}
}
}
But I'd get a NullPointerException on the synchronized(from) line.
I also tried this in the transfer method (and account had a ReentrantLock object inside it). But this time I'd get a NullPointerException on the line that reads from.getLock().unlock()
public void transfer(Account from, Account to, double amount){
while(true){
try{
if(from.getLock().tryLock()){
try{
if(to.getLock().tryLock()){
from.withdraw(amount);
to.withdraw(amount);
break;
}
} finally {
to.getLock().unlock();
}
}
} finally{
from.getLock().unlock();
}
Random random = new Random();
int i = random.nextInt(1000);
try {
Thread.sleep(1000 + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

using semaphores for multithreading

Good Day!
I need to solve synchronization problem using semaphores. I've read many tutorials and I now know that I should use a release method and am acquire method, however, i don't know where to use them in the code. could you please help me or link me to a useful tutorial.
I have class Account:
public class Account {
protected double balance;
public synchronized void withdraw(double amount) {
this.balance = this.balance - amount;
}
public synchronized void deposit(double amount) {
this.balance = this.balance + amount;
}
}
I have two threads: Depositer:
public class Depositer extends Thread {
// deposits $10 a 10 million times
protected Account account;
public Depositer(Account a) {
account = a;
}
#Override
public void run() {
for(int i = 0; i < 10000000; i++) {
account.deposit(10);
}
}
}
And Withdrawer:
public class Withdrawer extends Thread {
// withdraws $10 a 10 million times
protected Account account;
public Withdrawer(Account a) {
account = a;
}
#Override
public void run() {
for(int i = 0; i < 1000; i++) {
account.withdraw(10);
}
}
}
here is the main:
public class AccountManager {
public static void main(String[] args) {
// TODO Auto-generated method stub
Account [] account = new Account[2];
Depositor [] deposit = new Depositor[2];
Withdrawer [] withdraw = new Withdrawer[2];
// The birth of 10 accounts
account[0] = new Account(1234,"Mike",1000);
account[1] = new Account(2345,"Adam",2000);
// The birth of 10 depositors
deposit[0] = new Depositor(account[0]);
deposit[1] = new Depositor(account[1]);
// The birth of 10 withdraws
withdraw[0] = new Withdrawer(account[0]);
withdraw[1] = new Withdrawer(account[1]);
for(int i=0; i<2; i++)
{
deposit[i].start();
withdraw[i].start();
}
for(int i=0; i<2; i++){
try {
deposit[i].join();
withdraw[i].join();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Using a semapahore for your example could look like this:
import java.util.concurrent.Semaphore;
public class Account {
private Semaphore semaphore = new Semaphore(1);
private double balance = 0;
public void withdraw(double amount){
deposit(amount * -1);
}
public void deposit(double amount){
semaphore.acquireUninterruptibly();
balance += amount;
semaphore.release();
}
}
This example is very similar semantically to the synchronized locking one as it sets up a single Semaphore per Account instance (similar to the single mutex available for locking on an object instance). It also waits uninterruptibly (i.e. forever) to acquire a permit, similar to the under the hood code that tries to acquire a lock on an object. If you didn't want to wait forever, you could change your impl to something like this:
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class Account {
private Semaphore semaphore = new Semaphore(1);
private double balance = 0;
public void withdraw(double amount){
deposit(amount * -1);
}
public void deposit(double amount){
try {
semaphore.tryAcquire(1, TimeUnit.SECONDS);
balance += amount;
semaphore.release();
}
catch (InterruptedException e) {
//Probably want to throw a more specific exception type here...
throw new RuntimeException("Timed out waiting for an account balance...");
}
}
}
In this example, you will only want up to 1 second to acquire a permit, and throw an exception if that does not happen.
I'm not sure if caught your problem properly, but I'll give it a shot.
Your Account class is already thread safe as you are using the 'synchronized' keyword for the withdraw and deposit methods. When a 'synchronized' method is called it locks on 'this', so any two 'synchronized' methods will never run at the same time for one instance of 'Account'.
But if you want to be able to read the balance of one account you should add an accessor that also is synchronized. In that case the balance could only be read by one thread at a time, this could be changed by using a 'ReentrantReadWriteLock'. Here is a code on how you would use it:
class Account {
private double balance;
private ReentrantReadWriteLock balanceLock = new ReentrantReadWriteLock();
public void withdraw(double amount) {
try {
balanceLock.writeLock().lock();
this.balance = this.balance - amount;
}
finally {
balanceLock.writeLock().unlock();
}
}
public void deposit(double amount) {
try {
balanceLock.writeLock().lock();
this.balance = this.balance + amount;
}
finally {
balanceLock.writeLock().unlock();
}
}
public double getBalance() {
try {
balanceLock.readLock().lock();
return this.balance;
}
finally {
balanceLock.readLock().unlock();
}
}
}
In this case several threads can be reading the balance at a time, but only one thread at a time could change the balance.

Avoid Deadlock example

I am wondering what are the alternative ways to avoid deadlock in the following example. The following example is a typical bank account transferring deadlock problem. What are some of the better approaches to solve it in practice ?
class Account {
double balance;
int id;
public Account(int id, double balance){
this.balance = balance;
this.id = id;
}
void withdraw(double amount){
balance -= amount;
}
void deposit(double amount){
balance += amount;
}
}
class Main{
public static void main(String [] args){
final Account a = new Account(1,1000);
final Account b = new Account(2,300);
Thread a = new Thread(){
public void run(){
transfer(a,b,200);
}
};
Thread b = new Thread(){
public void run(){
transfer(b,a,300);
}
};
a.start();
b.start();
}
public static void transfer(Account from, Account to, double amount){
synchronized(from){
synchronized(to){
from.withdraw(amount);
to.deposit(amount);
}
}
}
}
I am wondering if the deadlock issue will be solved if I separate the nested lock out in my transfer method like the following
synchronized(from){
from.withdraw(amount);
}
synchronized(to){
to.deposit(amount);
}
Sort the accounts. The dead lock is from the ordering of the accounts (a,b vs b,a).
So try:
public static void transfer(Account from, Account to, double amount){
Account first = from;
Account second = to;
if (first.compareTo(second) < 0) {
// Swap them
first = to;
second = from;
}
synchronized(first){
synchronized(second){
from.withdraw(amount);
to.deposit(amount);
}
}
}
In addition to the solution of lock ordered you can also avoid the deadlock by synchronizing on a private static final lock object before performing any account transfers.
class Account{
double balance;
int id;
private static final Object lock = new Object();
....
public static void transfer(Account from, Account to, double amount){
synchronized(lock)
{
from.withdraw(amount);
to.deposit(amount);
}
}
This solution has the problem that a private static lock restricts the system to performing transfers "sequentially".
Another one can be if each Account has a ReentrantLock:
private final Lock lock = new ReentrantLock();
public static void transfer(Account from, Account to, double amount)
{
while(true)
{
if(from.lock.tryLock()){
try {
if (to.lock.tryLock()){
try{
from.withdraw(amount);
to.deposit(amount);
break;
}
finally {
to.lock.unlock();
}
}
}
finally {
from.lock.unlock();
}
int n = number.nextInt(1000);
int TIME = 1000 + n; // 1 second + random delay to prevent livelock
Thread.sleep(TIME);
}
}
Deadlock does not occur in this approach because those locks will never be held indefinitely. If the current object's lock is acquired but the second lock is unavailable, the first lock is released and the thread sleeps for some specified amount of time before attempting to reacquire the lock.
This is a classic question. I see two possible solutions:
To sort accounts and synchronize at account which has an id lower than another one.
This method mentioned in the bible of concurrency Java Concurrency in Practice in chapter 10. In this book authors use system hash code to distinguish the accounts. See java.lang.System#identityHashCode.
The second solution is mentioned by you - yes you can avoid nested synchronized blocks and your code will not lead to deadlock. But in that case the processing might have some problems because if you withdraw money from the first account the second account may be locked for any significant time and probably you will need to put money back to the first account. That's not good and because that nested synchronization and the lock of two accounts is better and more commonly used solution.
You can also create separate lock for each Account (in Account class) and then before doing transaction acquire both locks. Take a look:
private boolean acquireLocks(Account anotherAccount) {
boolean fromAccountLock = false;
boolean toAccountLock = false;
try {
fromAccountLock = getLock().tryLock();
toAccountLock = anotherAccount.getLock().tryLock();
} finally {
if (!(fromAccountLock && toAccountLock)) {
if (fromAccountLock) {
getLock().unlock();
}
if (toAccountLock) {
anotherAccount.getLock().unlock();
}
}
}
return fromAccountLock && toAccountLock;
}
After get two locks you can do transfer without worrying about safe.
public static void transfer(Acc from, Acc to, double amount) {
if (from.acquireLocks(to)) {
try {
from.withdraw(amount);
to.deposit(amount);
} finally {
from.getLock().unlock();
to.getLock().unlock();
}
} else {
System.out.println(threadName + " cant get Lock, try again!");
// sleep here for random amount of time and try do it again
transfer(from, to, amount);
}
}
Here is the solution for the problem stated.
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class FixDeadLock1 {
private class Account {
private final Lock lock = new ReentrantLock();
#SuppressWarnings("unused")
double balance;
#SuppressWarnings("unused")
int id;
public Account(int id, double balance) {
this.balance = balance;
this.id = id;
}
void withdraw(double amount) {
this.balance -= amount;
}
void deposit(double amount) {
balance += amount;
}
}
private class Transfer {
void transfer(Account fromAccount, Account toAccount, double amount) {
/*
* synchronized (fromAccount) { synchronized (toAccount) {
* fromAccount.withdraw(amount); toAccount.deposit(amount); } }
*/
if (impendingTransaction(fromAccount, toAccount)) {
try {
System.out.format("Transaction Begins from:%d to:%d\n",
fromAccount.id, toAccount.id);
fromAccount.withdraw(amount);
toAccount.deposit(amount);
} finally {
fromAccount.lock.unlock();
toAccount.lock.unlock();
}
} else {
System.out.println("Unable to begin transaction");
}
}
boolean impendingTransaction(Account fromAccount, Account toAccount) {
Boolean fromAccountLock = false;
Boolean toAccountLock = false;
try {
fromAccountLock = fromAccount.lock.tryLock();
toAccountLock = toAccount.lock.tryLock();
} finally {
if (!(fromAccountLock && toAccountLock)) {
if (fromAccountLock) {
fromAccount.lock.unlock();
}
if (toAccountLock) {
toAccount.lock.unlock();
}
}
}
return fromAccountLock && toAccountLock;
}
}
private class WrapperTransfer implements Runnable {
private Account fromAccount;
private Account toAccount;
private double amount;
public WrapperTransfer(Account fromAccount,Account toAccount,double amount){
this.fromAccount = fromAccount;
this.toAccount = toAccount;
this.amount = amount;
}
public void run(){
Random random = new Random();
try {
int n = random.nextInt(1000);
int TIME = 1000 + n; // 1 second + random delay to prevent livelock
Thread.sleep(TIME);
} catch (InterruptedException e) {}
new Transfer().transfer(fromAccount, toAccount, amount);
}
}
public void initiateDeadLockTransfer() {
Account from = new Account(1, 1000);
Account to = new Account(2, 300);
new Thread(new WrapperTransfer(from,to,200)).start();
new Thread(new WrapperTransfer(to,from,300)).start();
}
public static void main(String[] args) {
new FixDeadLock1().initiateDeadLockTransfer();
}
}
There are three requirements you must satisfy:
Consistently reduce the contents of one account by the specified amount.
Consistently increase the contents of the other account by the specified amount.
If one of the above is successful, the other must also be successful.
You can achieve 1. and 2. by using Atomics, but you will have to use something other that double as there is no AtomicDouble. AtomicLong would probably be your best bet.
So you're left with your third requirement - if one succeeds the other must succeed. There is a simple technique that works superbly with atomics and that is using the getAndAdd methods.
class Account {
AtomicLong balance = new AtomicLong ();
}
...
Long oldDebtor = null;
Long oldCreditor = null;
try {
// Increase one.
oldDebtor = debtor.balance.getAndAdd(value);
// Decrease the other.
oldCreditor = creditor.balance.gtAndAdd(-value);
} catch (Exception e) {
// Most likely (but still incredibly unlikely) InterruptedException but theoretically anything.
// Roll back
if ( oldDebtor != null ) {
debtor.getAndAdd(-value);
}
if ( oldCreditor != null ) {
creditor.getAndAdd(value);
}
// Re-throw after cleanup.
throw (e);
}

Categories