Square CSS

Friday, November 16, 2018

Java Multithreading : Synchronization (Method Level)

In multithreading, synchronization is used to allow only one thread at a time to access the shared resource.

Uses of Synchronization keyword in Java :

  • To prevent the other thread to interface with the current thread execution.
  • To maintain consistency where multiple threads are accessing the same resource.

Synchronization can be applied in three ways :

  • Method level synchronization
  • Synchronization block
  • Static Synchronization

Method Level Synchronization :


In method level synchronization the method is marked with synchronization keyword.
In this case, the lock is acquired on the object. The lock is released when the execution of the synchronization method is completed.

Example of method level Synchronization :


Below is the program in which inc() method is called simultaneously by the two threads t1 and t2.
The inc method is incrementing the count by 1. The count ++ is being performed in the inc() method. The count++ is nothing but count = count+1. If this process is performed without synchronized keyword then the count is not coming 10000 but it is coming less than that.



Why this is happening?


Here inc() method is performing count++ or in other terms count=count+1. 
Suppose for one thread t1 (let) count be 355 suddenly thread t2 also entered inc() method at the same time t2 also read count as 355 only. At this moment t1 performed count=355+1 and t2 also did the same. The result after inc() method execution for t1 and t2 at this step will be count=356 only. 
But if t1 would have executed first then count would have been 356 and t2 when tried to execute then it would have come out with the result of count as 357.

Let's apply the Synchronized key.



Using the synchronized key on method level the result came correct as 10000.


Refer the video tutorial :





                    The concepts of the volatile key are often misunderstood and often ... 

No comments:

Post a Comment

Some Algorithms

Algorithm: Tower of Hanoi

Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

Popular Posts