Synchronization in Java - Synchronized keyword
Synchronized method and 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;
}
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.
Follow us: www.facebook.com/javainstance
Follow us: www.facebook.com/javainstance
Synchronization in Java - Synchronized keyword
Reviewed by JavaInstance
on
6:50:00 AM
Rating:
Reviewed by JavaInstance
on
6:50:00 AM
Rating:

Good info on Java. Thanks for sharing and keep updating.
ReplyDeleteB.Com Project Center in Chennai | B.Com Project Center in Velachery
Thanks you so much for sharing this Java Synchronization Concept .
ReplyDeleteYou explained very well.
Nice post..I have learn so many things from your blog..Keep sharing such a wonderful information..
ReplyDeleteBest Photoshop Summer Courses in Guindy | No.1 Technical Boot Camp in Chennai
This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information, this is useful to me…
ReplyDeleteSoftware Testing Summer Courses in Adyar | Summer Courses in Velachery | Java Summer Courses in Perungudi
Thanks for this grateful information. all this information is very important to all the users and can be used good at all this process.
ReplyDeleteSelenium Summer Courses in Velachery | Web designing summer Classes in Adyar | Android summer Courses in OMR
This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information, this is useful to me…
ReplyDeleteGraphics Designing Training Institute in chennai | Best Multimedia courses in Velachery
ReplyDeleteThanks 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
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
ReplyDeleteAwesome Blog with useful Concept. Keep Blogging. UIPath Certification Exam Center in Chennai | BluePrism Exam Center in Chennai | Automation Exam Center in Chennai
ReplyDeleteExcellent blog with strong content. Thanks for sharing such useful information..
ReplyDeleteJava training in Chennai
Very useful and information content has been shared out here, Thanks for sharing it.
ReplyDeleteVisit Learn Digital Academy for more information on Digital marketing course in Bangalore.
You made me to feel fresh after reading your blog. Thanks for sharing.
ReplyDeleteSelenium training in Chennai
Selenium Courses in Chennai
best ios training in chennai
Digital Marketing Training in Chennai
JAVA J2EE Training Institutes in Chennai
Loadrunner course in Chennai
Qtp training institutes in chennai
I am really enjoying reading your well written articles.
ReplyDeleteIt 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
ReplyDeleteNice content! This post is having more kinds of information about this topic and thanks for providing a great post with huge knowledge. Keep sharing with us...
Embedded System Course Chennai
Embedded System Courses in Chennai
Excel Training in Chennai
Corporate Training in Chennai
Oracle Training in Chennai
Unix Training in Chennai
Power BI Training in Chennai
Embedded System Course Chennai
Embedded Training in Chennai
Excellent post and I really glad to saw your worthful post. I am waiting for your next post and keep updating unique details in this topic.
ReplyDeleteSpark Training in Chennai
Spark Training Academy
Tableau Training in Chennai
Oracle DBA Training in Chennai
Linux Training in Chennai
Pega Training in Chennai
Primavera Training in Chennai
Social Media Marketing Courses in Chennai
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.
ReplyDeleteVMware 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
Pretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.
ReplyDeleteJava Classes in Chennai
Java Classes in Chennai
Java Institutes in Bangalore
Best Java Training in Coimbatore
Best Java Training Institute in Madurai
Java Course in Madurai
Java Training in Madurai
Nice article. I liked very much. All the informations given by you are really helpful for my research. keep on posting your views.
ReplyDeleteccna training institute in coimbatore
best ccna training institute in coimbatore
best ccna institute in madurai
ccna training madurai
best ccna institute in bangalore
ccna institute in bangalore