Friday, 31 October 2014

Threads safety reality check

Okay, now this post is dedicated to those who have just begun reading about threads and processes in java. There is a very simple and interesting code that follows , which demonstrates the synchronization problem with threads.
Before continuing to the next section ,you should be really clear about what threads are , how they work and how the operating system schedules the threads .
For a recap, threads in java can be created in 2 ways :

  1. implementing the Runnable interface
  2. extending the Thread class
Now here is the case :

  • Let us suppose that there is a joint account in a bank and the joint account is accessible by Mr.X and Mr.Y. 
  • Now the available balance in the account is 400$
  • The withdrawal can only be done if Current account balance is greater than the withdrawal amount.
  • Here Mr.X first withdraws some money using 1 thread and then Mr.B withdraws some money using another thread.

**Now please do compile and run the program yourself to see what the output is .
I am sure that you will be surprised on getting the output .


PROGRAM DESCRIPTION :

An Account class is created and a static member curr_bal is initialized to 400 . A withdraw() is used for withdrawing from the account .
Two threads namely Thread1 and Thread2 are run .Basically the 2 joint account holders use these threads to carry out their transactions.




OUTPUT :

** Spend a moment thinking what just happened , before reading the discussions section.
Basically you should be asking yourself ,that firstly how was the second thread even allowed to do a transaction since the condition (current balance > withdrawal amount ) would not be met after the first thread completes transaction ,as the current balance would then become 100.
(300$ + 200$=500$ total ) was deducted from 400$ ...leaving to negative balance . How on earth did we have a negative balance !!!
DISCUSSIONS:

Now if you are very new to threads, you will be racking your brains over this , and it is very much desired ,that you think over this as its only that when you face a problem , that you search looking for a solution .
Now isn't the problem here a grave one ? Just try to imagine how much losses would a bank incur if the programmers coded in the similar fashion and the amount was billions of dollars . Surely makes an impact right ? .

Ok so now getting straight to the point . What basically happens here that you have 2 threads accessing the same resource that is CURRENT BALANCE . Why do we use threads in the first place ? CONCURRENCY !! . Imagine a net banking system managed by some bank . Now if you didnt have a concurrent solution then all your customers would be queuing up to complete their transactions one after another and if one was transaction messed up , the entire queue of customers would have to wait the entire time . We use threads in such scenario so that several customers can operate at the same time using the same portal .

Coming back to the point . Concurrency along with its advantage has some disadvantages . Here
the first thread is started first.and it tries to make the withdrawal .... the condition (curr_bal>amt) is fulfilled , so it enters the block .Now come the catch . This thread is then made to sleep for 1000ms(1 sec) i.e the thread stays inactive basically during the sleep time .

So the balance  is not yet updated and adjusted and the withdrawal is yet not complete . what happens now is that , while the first thread is sleeping ,the second thread tried to make the withdrawal. now again the condition checking is performed (curr_bal> amt) . THIS IS TRUE AGAIN !! because the thread1 hasn't yet woken up and updated the new current balance . So Thread2 gets passed the condition and now the Thread1 wakes up and at the same time Thread2 is put to sleep .
Now the deductions takes place one after another and the final balance that shows up is -100.
Well done BANK !! you've hired the worlds best programmers to GIVE YOU GOOD LOSS .
Hire me instead lol :P .

In case of any doubts , make use of the comments section .
If you have enjoyed reading , you can contribute by typing in your valuable feedback .


No comments:

Post a Comment