Synchronization in Java

Introduction

Synchronization in Java is an important concept since Java is a multi-threaded language, It has the capability to control the access of multiple threads to any shared resource.

Synchronization in Java is possible by using Java keywords “synchronized”. It is a better option when requirement is only one thread to access the shared resource at a time.

The main advantage of synchronized keywords is we can resolve data inconsistency problems.

 

Why use Synchronization

The main advantage of synchronized keywords is we can resolve data inconsistency problems. To using Synchronization we can prevent thread interference.

The main limitation of a synchronized keyword is it increasing the waiting time of threads and affects the perforation of the system. Hence if there is no specific requirement it’s never recommended to use synchronized keyword.

 

Types of Synchronization

There are two types of synchronization

  1. Process Synchronization
  2. Thread Synchronization

 

Thread Synchronization:

Thread Synchronization is the capability to control the access of multiple threads to a shared resource, you need to ensure that the resource will be used by only one thread at a time.

Types of thread Synchronization:

There are two types of thread synchronization mutual exclusive and inter-thread communication.

  1. Mutual Exclusive
  2. Inter-thread communication

 

Mutual Exclusive is three types

  1. Synchronized method.
  2. Synchronized block.
  3. Static synchronization.

 

Concept of Lock in Java:

Every Object in java has a unique lock Synchronized concept, internally implemented by using this lock concept.

Whenever we are using Synchronized then only lock concept will come into the picture.

 

Synchronized method:

If a method declared as Synchronized then at a time only one thread is allowed to execute that method on the given object.

If a thread wants to execute any Synchronized method on any given object first it has to get lock of that object. Once the thread gets a lock then it is allowed to execute any Synchronized method on that object.

Once the Synchronized method completes than automatically the lock will be released.

While a thread executing any Synchronized method on the given object the reaming threads are not allowed to execute any Synchronized method on the given object simultaneously. But reaming thread is allowed to execute any Non-Synchronized methods simultaneously(lock concept is implemented based on the object but not based on method).

 

Let’s first see Example of without Synchronized method programming.

package com.technocalRound;

class Counting {
void printCounting(int n) {// No synchronized method
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}

}
}

class MyThread1 extends Thread {
Counting c;

MyThread1(Counting c) {
this.c = c;
}

public void run() {
c.printCounting(5);
}

}

class MyThread2 extends Thread {
Counting c;

MyThread2(Counting c) {
this.c = c;
}

public void run() {
c.printCounting(100);
}
}

class TestSynchronization1 {
public static void main(String args[]) {
Counting obj = new Counting();// only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:

5
10
15
20
25
100
200
300
400

 

Example with Synchronized method programing.

package com.technocalRound;

class Counting {
synchronized void printCounting(int n) {// synchronized method
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}

}
}

class MyThread1 extends Thread {
Counting c;

MyThread1(Counting c) {
this.c = c;
}

public void run() {
c.printCounting(5);
}

}

class MyThread2 extends Thread {
Counting c;

MyThread2(Counting c) {
this.c = c;
}

public void run() {
c.printCounting(100);
}
}

public class Example2 {
public static void main(String args[]) {
Counting obj = new Counting();// only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:

5
10
15
20
25
100
200
300
400

 

Synchronized block:

Synchronized block can be used to perform synchronization on very few lines of code of the method.

If very few lines of code required to Synchronization then it is never recommended to declare the entire method as Synchronized. We have to declare only those few lines of code inside the synchronized block.

If you put all the codes of the method in the synchronized block, it will work the same as the synchronized method.

The main advantage of a synchronized block over a synchronized method is, it reduces the waiting time of the thread and improves the performance of the system.

 

Example 1: We can declare a synchronized block to get the current object as follows.

synchronized (this)
{
---------
---------
---------
}

If the thread got lock of the current object, then only it will allow executing this bock.

 

Example 2: To get a lock of a particular object b and we can declare a synchronized block as follows

synchronized(b)
{
---------
---------
---------
}

If the thread got lock of the ‘b’ object, then only it will allow executing that bock.

 

Example 3: To get class level lock we can declare a synchronized block as follows

synchronized(className.class)
{
---------
---------
---------
}

If the thread got class level lock of className(Example) class then only it will be allowed to execute that bock.

Every object in java has a unique lock. But a thread can acquire more than one lock at a time( through different objects).

 

Example of Synchronized block:

package com.technocalRound;

class Counting {

void printCounting(int n) {
synchronized (this) {// synchronized block
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
}// end of the method
}

class MyThread1 extends Thread {
Counting c;

MyThread1(Counting c) {
this.c = c;
}

public void run() {
c.printCounting(5);
}

}

class MyThread2 extends Thread {
Counting c;

MyThread2(Counting c) {
this.c = c;
}

public void run() {
c.printCounting(100);
}
}

public class Example2 {
public static void main(String args[]) {
Counting obj = new Counting();// only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:

 5
10
15
20
25
100
200
300
400
500

 

ClassLavel Lock

Every class in Java has a unique lock. If the thread wants to execute a static Synchronized method than it is required class level lock.

While a thread executing a static Synchronized method then the remaining threads are not allowed to execute any static Synchronized method of that class simultaneity.

But the remaining thread is allowed to execute the following methods Simultaneously.

  1. Normal Static methods
  2. Normal instance methods
  3. Synchronized instance methods.

There is no link between object-level lock and class level lock both are independent of each other.

 

Static Synchronization

If you make any static method as synchronized, the lock will be in the class.

Example of Static Synchronization.

package com.technocalRound;

class Counting {

synchronized static void printCounting(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
}
}
}
}

class MyThread1 extends Thread {
public void run() {
Counting.printCounting(1);
}
}

class MyThread2 extends Thread {
public void run() {
Counting.printCounting(10);
}
}


public class Example2 {
public static void main(String t[]) {
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.start();
t2.start();
}
}

Output:

1
2
3
4
5
10
20
30
40
50

 

Read More topics related to the collection.

 

Read more topics related to java

 

Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.

 

37 Replies to “Synchronization in Java”

  1. A lot of thanks for all your valuable hard work on this web page. Kate loves getting into investigation and it’s really easy to understand why. I know all of the dynamic medium you make insightful solutions on this web blog and as well as foster participation from people on that idea so our girl is certainly discovering a lot of things. Have fun with the remaining portion of the new year. You are conducting a powerful job.

  2. I am commenting to let you know of the fine encounter my friend’s daughter found reading your site. She figured out many issues, not to mention what it’s like to have a wonderful giving mindset to have men and women quite simply have an understanding of selected hard to do subject areas. You really exceeded our expected results. Thanks for providing those productive, trusted, informative as well as unique tips on your topic to Mary.

  3. A lot of thanks for all your efforts on this site. Gloria loves engaging in investigation and it’s easy to understand why. Almost all know all concerning the dynamic means you give helpful secrets on the web blog and as well encourage contribution from others on that concern plus our daughter is always discovering a lot. Have fun with the remaining portion of the new year. You’re the one conducting a good job.

  4. I am also writing to make you know what a impressive encounter my friend’s girl gained reading through your web page. She learned such a lot of things, with the inclusion of what it is like to possess an ideal teaching style to make the mediocre ones without hassle master specified tricky topics. You undoubtedly surpassed visitors’ expected results. Thanks for showing those valuable, trustworthy, revealing not to mention unique tips on your topic to Sandra.

  5. I happen to be writing to make you understand what a terrific experience our princess went through visiting yuor web blog. She realized such a lot of things, with the inclusion of what it is like to possess an incredible teaching style to make the others without hassle thoroughly grasp various tricky topics. You undoubtedly surpassed visitors’ expected results. Thanks for showing those valuable, trustworthy, revealing not to mention unique tips on your topic to Sandra.

  6. I’m also commenting to let you be aware of of the cool discovery my child encountered checking your blog. She came to understand a wide variety of details, most notably how it is like to have an amazing helping mood to let other folks smoothly know just exactly several multifaceted subject matter. You truly exceeded our own expectations. Thank you for offering these necessary, safe, explanatory and even fun tips about this topic to Julie.

  7. I precisely had to say thanks all over again. I’m not certain the things I could possibly have created in the absence of the actual creative ideas discussed by you concerning such concern. It absolutely was a real depressing concern for me personally, but considering a new professional fashion you handled it forced me to cry for delight. I’m grateful for the assistance and as well , expect you comprehend what a powerful job that you are carrying out educating men and women by way of a web site. I am certain you’ve never come across all of us.

  8. I’m commenting to let you be aware of of the beneficial discovery my child developed browsing the blog. She came to find a lot of details, including how it is like to have a great coaching character to get certain people completely comprehend a number of complex issues. You actually did more than her desires. I appreciate you for coming up with such essential, dependable, edifying and cool guidance on that topic to Ethel.

  9. Thanks for the useful information on credit repair on your web-site. The thing I would offer as advice to people will be to give up a mentality they will buy at this moment and pay back later. As being a society most people tend to repeat this for many factors. This includes family vacations, furniture, plus items we really want to have. However, you must separate a person’s wants from the needs. When you’re working to fix your credit score you really have to make some trade-offs. For example you possibly can shop online to economize or you can click on second hand suppliers instead of highly-priced department stores to get clothing.

  10. I simply wished to thank you very much yet again. I do not know what I would have used without those tips and hints shown by you relating to this theme. Previously it was the traumatic setting in my view, nevertheless viewing your well-written technique you treated the issue took me to weep with joy. Now i am thankful for your work as well as trust you recognize what an amazing job you were undertaking training the others with the aid of your website. Probably you haven’t met any of us.

  11. I enjoy you because of all of the effort on this blog. Debby delights in conducting internet research and it’s easy to see why. A number of us hear all about the compelling form you create both useful and interesting guidelines by means of the blog and boost contribution from other ones about this area of interest and my child has been becoming educated a great deal. Enjoy the remaining portion of the new year. You’re carrying out a fabulous job.

  12. Thanks for the suggestions about credit repair on this particular web-site. The things i would offer as advice to people is usually to give up this mentality that they buy at this point and fork out later. As being a society most of us tend to make this happen for many factors. This includes trips, furniture, in addition to items we’d like. However, it is advisable to separate one’s wants from the needs. As long as you’re working to raise your credit ranking score you really have to make some trade-offs. For example you may shop online to economize or you can check out second hand outlets instead of high priced department stores intended for clothing.

  13. I pay a visit day-to-day some websites and information sites to read articles or reviews, but this web site offers feature based articles.| Emylee Claire Birmingham

Leave a Reply

Your email address will not be published.