Synchronization in Java - Synchronized keyword

Synchronized method and Synchronized block

Synchronized method vs Synchronized block
We have learnt how to create thread in Java.In this post, we are going to see how to use synchronization in Java.
Synchronization is a very important concept in a multithreading environment.Synchronization is used when we want the resource to be accessed by a single thread at a time.Thus synchronization is useful to avoid the concurrency issues.

Problem without  Synchronization 

Let's write a program to understand the problem without Synchronization.In below program, we have created two thread using anonymous class and both are trying to increment the counter value by calling a method.

  • Thread.sleep() is used to simulate the real time process which takes some time.
  • join() is used to print counter value once both thread complete the task.
If we run below program we will get different output every time because both threads are trying to update the counter without waiting for each other thus leading to the race condition.A race condition occurs when two or more thread can access shared data and try to change it at the same time.


Program:

package com.javainstance;

/**
 * @author javainstance
 *
 */
public class MultiThread {


private int counter=0;

public void countIncrementor(){

counter=counter+1;
}

public void TaskManager(){


Thread threadOne=new Thread(new Runnable() {

@Override
public void run() {
for(int i=0;i<100;i++){
  try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  

countIncrementor();
}


}
});

Thread threadTwo=new Thread(new Runnable() {

@Override
public void run() {
for(int i=0;i<100;i++){
  try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  
countIncrementor();
}


}
});

threadOne.start();
threadTwo.start();
try {
        threadOne.join();
threadTwo.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {

MultiThread multiThread=new MultiThread();
multiThread.TaskManager();

System.out.println("Counter is:"+ multiThread.counter);



}


}


Output:

Counter is:186
Counter is:185
Counter is:179

Synchronization using Synchronized method

In below above program, we just need to modify countIncrementor() method to synchronized method.

public synchronized  void countIncrementor(){
counter=counter+1;
}

Now if we run the program every time we will get the same output.

Output:


Counter is:200

How Synchronization method works?

Every object in Java has a monitor lock.So whenever a thread calls any synchronized method it acquires the monitor lock on that object.Only one thread at a time can acquire an object lock when method releases the lock after execution then only other thread can acquire the lock.Thus in the multithreaded environment, we can avoid concurrency issue.

Synchronization using Synchronized block

We can also use synchronized block to obtain synchronization in Java.To use synchronized block we have to modify countIncrementor() method as below.In synchronized block, we have to pass a parameter object of which monitor lock will be acquired by the thread.Here this keyword denotes MultiThread class object.

public void countIncrementor() {
synchronized (this) {

counter = counter + 1;
}
}


Which is better synchronized method or synchronized block ?

It depends on the code or task which you are going to define inside the synchronized method or synchronized block.However synchronized block has an advantage over synchronized method that it locks only critical part of the code which actually needed to be thread safe instead of the full method.Thus it is more efficient in most of the cases.

Disadvantage of synchronized keyword

The major disadvantage of synchronized keyword is that it avoid the concurrent read also from multiple thread thus leads the performance issue.

Volatile keyword in Java

Give your suggestion in comments.
If you like the post Share with your friends on social network.









Synchronization in Java - Synchronized keyword Synchronization in Java -  Synchronized keyword Reviewed by JavaInstance on 6:50:00 AM Rating: 5

18 comments:

  1. Thanks you so much for sharing this Java Synchronization Concept .
    You explained very well.

    ReplyDelete
  2. Nice post..I have learn so many things from your blog..Keep sharing such a wonderful information..
    Best Photoshop Summer Courses in Guindy | No.1 Technical Boot Camp in Chennai

    ReplyDelete
  3. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information, this is useful to me…
    Software Testing Summer Courses in Adyar | Summer Courses in Velachery | Java Summer Courses in Perungudi

    ReplyDelete
  4. Thanks for this grateful information. all this information is very important to all the users and can be used good at all this process.
    Selenium Summer Courses in Velachery | Web designing summer Classes in Adyar | Android summer Courses in OMR

    ReplyDelete
  5. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information, this is useful to me…
    Graphics Designing Training Institute in chennai | Best Multimedia courses in Velachery

    ReplyDelete

  6. Thanks for this grateful information. all this information is very important to all the users and can be used good at all this process.
    ISTQB Certification Training in Chennai | Java Exam Center in Chennai | Microsoft Dot net Certification in Chennai

    ReplyDelete
  7. I like your blog format as you create user engagement in the complete article. It seems round up of all published posts. Thanks for sharing, such a nice article. UIPath Exam Center in Chennai | Automation Anywhere Exam Center in Chennai | Blue Prism Exam Center in Chennai

    ReplyDelete
  8. Excellent blog with strong content. Thanks for sharing such useful information..

    Java training in Chennai

    ReplyDelete
  9. Very useful and information content has been shared out here, Thanks for sharing it.
    Visit Learn Digital Academy for more information on Digital marketing course in Bangalore.

    ReplyDelete
  10. I am really enjoying reading your well written articles.
    It looks like you spend a lot of effort and time on your blog.
    I have bookmarked it and I am looking forward to reading new articles.Keep up the good work..
    Digital Marketing Course in Chennai
    JAVA Training in Chennai
    Java training institute in chennai

    ReplyDelete
  11. I am really enjoying reading your well-written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
    VMware Training in Chennai
    VMware Training
    Vmware cloud certification
    R Training in Chennai
    RPA Training in Chennai
    DevOps certification in Chennai
    VMWare Training in Anna Nagar
    VMWare Training in T Nagar
    VMWare Training in Adyar

    ReplyDelete

Powered by Blogger.