Thursday, June 3, 2010

Synchronization in Java

Synchronization keyword is very useful while working with web-application on multithreaded environment.

Let us take an example of bank account where lots of transaction occurred simultaneously. Suppose you are having Rs.10000 in your bank account and you withdraw Rs.1000 and in the same time you are getting some interest of money Rs.600 and your cheque has debited of Rs.9100 from your account.

There are 3 transactions (threads),

1) T1 --> withdraw Rs.1000
2) T2 --> Interest Rs.600
2) T3 --> cheque debited Rs.9100


In these scenario, how do you know the latest value of bank account. If you want correct value of your bank account, you need to make the account value synchronized. In synchronization, each transaction makes a lock. When any transaction makes a lock, other transactions wait until the lock has been released.

Now we want to explore something more on synchronization keyword. What are the cases when one synchronization block will wait for other block and when one synchronization block will not wait for other synchronized block?

In this case you can go through the following link,
http://www.herongyang.com/java/Synchronization-Support-in-Java-synchronized.html

No comments: