Sunday 6 November 2016

Java Source World: Synchronization in Java

Synchronization in Java | Java Source World

                                                                                   Java Source World                   A Java quick reference blog



Synchronization in Java



Mechanism to control the access of shared resource by multiple threads.
When multiple thread access any shared resource simultaneously , it may result in data in consistency. Hence we can use synchronization concept to ensure the data consistency.
Synchronization can be achieved by using a modifier called 'synchronized'. 
It can be implemented in 2 ways

  • Synchronized Method
  • Synchronized Block/statement. 

Synchronized Method:



When we need to synchronize a method , we can do it by adding modifier "synchronized" to method header.
We can define synchronize methods when we have access to source code.

A java class can have multiple synchronized methods. But only one synchronized method can execute at any point of time.Hence the shared resource of that Class/Object can be assured through that method. This guarantees that no 2 threads can access shared resource simultaneously.

When a thread is executing a synchronized method it will not release the CPU unless it finishes the execution completely.Even if the thread goes to Block/Wait/sleep state.


Example: Synchronizing a method

       synchronized public void withdraw(double amount){
                  //do something
            }



Synchronized Block/statement:


When we do not have access to source code we cannot synchronize methods in that class.This kind of situation will arise when we third party libraries purchased from some vendor.It ensure data consistency.

Example: Synchronizing a block or statement.

         synchronized(obj){
                  obj.run();
            }

In the above code, obj is the reference of the object.



There is no guarantee that thread priority works always. If JVM doesn't honor the specified priority then priority doesn't work.



Other posts you may like to read:



                                                                      Java Source World              A Java quick reference blog



No comments:

Post a Comment