Thursday, 25 February 2016

Corrupting data by not locking the object- Multithreading in Java Lesson 1

Corrupting data by not locking the object- Multithreading in Java


This program shows how the data is get corrupted when two threads share a single object. We have one object account of class BankAccount1 which is shared by two threads threadNamedJack and threadNamedJill. Both of these threads try to modify the object account and consequenctly corrupts the data. In the utility method makeWithdrawal(int amountToWithdraw) we have a condition

 if (account.getBankBalance() >= amountToWithdraw) 

to make sure that the account is not overdrawn but if we run the program and see the results we see that the account has been overdrawn. The solution is to lock the object when one of the threads is using it and relase the lock after this thread has finished its job and make it available for other threads. We do not use locks in this program but we will use it in the next version of this program.

To see the source code please click here.

No comments:

Post a Comment