Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best ways to write a method that updates two objects in a multithreaded java environment?

Suppose we have a class called AccountService that manages the state of accounts.

AccountService is defined as

interface AccountService{
 public void debit(account);
 public void credit(account);
 public void transfer(Account account, Account account1);

}

Given this definition, what is the best way to implement transfer() so that you can guarantee that transfer is an atomic operation.

I'm interested in answers that reference Java 1.4 code as well as answers that might use resources from java.util.concurrent in Java 5

like image 228
Daniel Honig Avatar asked Jun 02 '10 14:06

Daniel Honig


Video Answer


2 Answers

Synchronize on both Account objects and do the transfer. Make sure you always synchronize in the same order. In order to do so, make the Accounts implement Comparable, sort the two accounts, and synchronize in that order.

If you don't order the accounts, you run the possibility of deadlock if one thread transfers from A to B and another transfers from B to A.

This exact example is discussed on page 207 of Java Concurrency in Practice, a critical book for anybody doing multi-threaded Java development. The example code is available from the publisher's website:

  • Dynamic lock-ordering deadlock. (bad)
  • Inducing a lock ordering to avoid deadlock.
like image 179
Edward Dale Avatar answered Nov 01 '22 19:11

Edward Dale


A classic example very well explained here - http://www.javaworld.com/javaworld/jw-10-2001/jw-1012-deadlock.html?page=4

like image 32
Anton Avatar answered Nov 01 '22 18:11

Anton