Synchronization In Java

Synchronization in Java is the process that allows only one thread at a particular time to complete a given task entirely. 

By default, the JVM gives control to all the threads present in the system to access the shared resource, due to which the system approaches race condition.

Now, let’s take a real-world example to understand the concept of race condition clearly and how you could avoid the same using Synchronization.

Imagine a classroom where three teachers are simultaneously present to teach the same class. In this scenario, the classroom acts as a shared resource, and the three teachers are the threads. All of them can’t teach at the same time. This scenario when looked at in the context of a computer language is referred to as Race Condition, where there are multiple threads present to do a given task.

To solve the above problem, we use Synchronization in Java. It is also a good practice especially when the threads update the data concurrently.

Why Do You Need to Use Synchronization in Java?

  1. To prevent thread interleaving or interference
  2. To provide consistency to the program

How Is It Carried Out?

Synchronization in Java is done by using the synchronized keyword. This keyword can be used on top of a method or a block.

Types of Synchronization

There are two types of Synchronization in Java, as mentioned below-

  • Process Synchronization

When multiple threads are executed simultaneously process synchronization ensures that they reach a particular state and agree to a certain set of actions.

  • Thread Synchronization

When multiple threads want to access the same resource, thread synchronization makes sure that only one thread gains access at a time.

Depicted below is an example of code to understand Thread Synchronization-

ThreadSynchronization.

Output

ThreadSynchronization_2

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

Mutual Exclusive

A mutex (short for mutual exclusion) is a type of object that is used to control access to a shared resource. Threads will request mutex access, and the mutex can only allow it access provided no other thread owns the mutex. When the mutex is released, other threads waiting in line may obtain access. If a thread already owns a mutex, and requests access again, it will be given continued access immediately. However, the thread must release the mutex the same number of times before other threads can obtain ownership.

In short, it helps in keeping the thread from interfering while sharing data. You can achieve mutual Exclusion in Java in the following three ways-

  • Synchronized Method

The general syntax of using the synchronized keyword in a method is given below-

<access modifier> synchronized method (parameter)

{

//code

}

First, look at an example of code where synchronization is not done.

SynchronizedMethod

Output

SynchronizedMethod_2.

In the above code, as you can see, both the statements are running simultaneously, which creates an inconsistency in the program. Just using the synchronized keyword before the method can easily solve this problem, as shown below.

SynchronizedMethod_3.

Output


SynchronizedMethod_4

When you add the keyword synchronized, it executes the first statement first and the second statement after that, and so on.

  • Synchronized Block

A synchronized block is simply a block that uses the synchronized keyword.

It is important to understand the difference between a synchronized method and a synchronized block.

Take an example where there is a method called method1 containing some instructions.

void method1

{

// This method contains some instructions

………

……..

……..

………

}

Now, if all these instructions present in method1 are not shareable by multiple threads simultaneously, then you must use the synchronized method as in the code above. 

But what if there is a set of instructions that are not shareable between multiple threads at a time, and the remaining instructions could be shared? 

Here comes the need to use the synchronized block. In this situation, the synchronized keyword should be added before those particular sets of instructions that are not shareable.

void method1

{

// ……… (these set of instructions are shareable between multiple threads at a given time)

………..

………..

synchronized …….. (these set of instructions are not shareable)

}

Here is an example of code to understand the synchronized block.

SynchronizedBlock

Output

SynchronizedBlock_2

  • Static Synchronization

In static synchronization, the lock and monitor belong to the class instead of an object. The memory for static methods is only assigned once during class loading. The whole class is blocked when a static method is being executed. As a result, other static synchronized methods are also obstructed. If one thread attempts to execute a static synchronized method, all other threads attempting to execute any static synchronized methods will be blocked.

Example for static synchronization-

StaticSynchronization

Output

StaticSynchronization_2.

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

Inter Thread Communication

Inter thread communication in Java is a method that allows several threads to communicate with one another. It provides an effective way for multiple threads to communicate with each other by minimizing CPU idle time. 

CPU idle time is a procedure that prevents CPU cycles from being wasted. When many threads are running at the same time, they may need to communicate with one another by sharing information. A thread exchanges data before or after changing its state. Communication between threads is vital in a variety of cases. 

For example; Assume there are two threads: A and B. Thread B executes its task using the data developed by Thread A. Thread B would waste several CPU cycles while it waits for Thread A to create data. On the other hand, threads A and B do not have to wait and check each other's status every time they complete their tasks if they engage with each other after they have finished their tasks, As a result, you would not waste CPU cycles either.

Locks in Java

A lock is a thread synchronization mechanism similar to synchronized blocks, except that locks can be more complex than Java's synchronized blocks. Locks are formed using synchronized blocks, so you can't get rid of the synchronized keyword entirely.

Multi-Threading Without Synchronization

In the following example, you do not use synchronization and instead create multiple threads that access the display method and generate random output.

Multi-threading

Output

Multi-threading_2

Multi-Threading With Synchronization

Multi-threading_3

Output

Multi-threading_4

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion

We hope this tutorial on the synchronization in Java helped you understand how it works and the examples gave you a practical walk-through that you’ll need.

Java today is one of the most popular and widely used programming languages, and expertise in it can open a wide range of excellent job opportunities for you. If you are interested in pursuing a career as a Java developer, Simplilearn’s Full Stack Java Developer Master’s program. This Full Stack Java Development boot-camp offers work-ready training in 30+ in-demand tools and skills with 20+ lesson-end, 6 phase-end projects, and 4 industry-aligned capstone projects. Do explore the course. Rest assured, it will be worth your time.

If you have any questions or have any feedback for us, write to us in the comment section below. We will review them and have a response ready for you in no time.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.