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

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


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:


You probably need to have a full transactions support (if it's a real application of course).

The difficulty of solution hardly depends on your environment. Describe your system in detail and we'll try to help you (what kind of application? does it use web-server? which web-server? what is used to store data? and so on)