Showing posts from April, 2017

Java Concurrency - Synchronization

In my last post we looked at running tasks across multiple threads, asynchronously using the ExecutorService. Accessing and manipulating an object from multiple threads simultaneously can pose a problem when the object in question holds state. If multiple threads attempt to modify shared state, behaviour can become unpredictable and result in data being left in an inconsistent state.

Unsynchronized Code Take the simple BankAccount class below. It holds state in the form of a balance, which can be increased and decreased using the credit and debit methods respectively. When used in a single threaded context this object will behave as expected, crediting and debiting the amounts specified.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16publicclassBankAccount { privatedouble balance; publicvoid credit(double amount){ balance = balance +amount; } publicvoid debit(double amount){ balance = balance - amount; } publicdouble getBalance(){ retur…