Introduction to Synchronization

Working with multi-threaded applications is a very complicated task in Java. Java developers usually have to keep various details into account while working with multi-threading. Various aspects, if not properly handled can disrupt the process.

One such case is when multiple threads in a single program try to access the same resource at the same time. For instance, a thread attempting to open a file to read data while another thread is trying to close it.

Such concurrency issues often result in various unexpected results. In such situations, no thread can properly operate and this can also lead to data corruption.

To cater to that, the access to the resources must be limited to one thread at a time to prevent multiple threads from accessing the same resource at the same time. Java programming language came up with a solution by offering the mechanism of synchronization to avoid such concurrency. It provides synchronized thread access to all the shared resources.

In this article, we will be discussing the synchronized keyword in Java that is used to implement the synchronization in Java. We will also explore various ways to use the Java synchronized keyword with aid of coding examples.

Synchronized keyword in Java

The process of restricting multiple threads and allowing a single thread at a time to access the shared data is called Synchronization. Java offers the mechanism of synchronization for multi-threading using synchronized blocks.

A synchronized block is declared in Java using the synchronized keyword. The synchronized blocks ensure that only one thread will be executed at a particular time. It allows only one thread at a time and no other thread can enter that synchronized block until the thread inside the block completes its execution and leaves the block.

 

The code below demonstrates the general syntax for declaring a block using the synchronized keyword in Java:

1. synchronized( lockObj)
2. {
3. 
4. // synchronized statements
5. 
6. }

The lockObj used here is a reference to an object whose lock is related to the synchronized statements.

Synchronization locks

The use of the Java synchronized keyword actually marks the block or a method as synchronizing on a specific object.

Every Java object created Inside the JVM, along with every Class that is loaded, gets an associated lock to prevent any other thread to access the resource.

After the Java synchronized keyword is applied on a block or a method, the active thread acquires the lock on the specified object before starting the execution of the code.

The lock is then released afterward either when the code execution finishes or either the thread is temporarily suspended.

Between the process of acquiring the lock and releasing it, a thread actually “owns” the lock. It means that other threads will have to wait to acquire the lock until the currently running thread does not release it.

This locking mechanism plays the primary role to prevent concurrency as due to this acquiring and releasing process, multiple threads will never get access at the same time.

Types of Synchronization in Java

The Java synchronization can be classified into the following two types:

1. Process Synchronization

Process Synchronization refers to the mechanism of sharing the resources between two or more processes while keeping checks for any inconsistencies in data.

The piece of code that is shared among different processes is often referred to as the Critical Section. There have been many solutions proposed to avoid this critical section problem. Among all the proposed solutions, the most popular way and widely used one is the Semaphores method.

2. Thread Synchronization

The concurrent execution of the critical resource multiple threads is referred to as the thread Synchronization. Thread is a subroutine that can execute independently within a process. A single process can have multiple threads and the process can also schedule all the threads for a resource making it a critical resource.

Uses of Synchronized keywords in Java

1. Synchronized Instance methods

When a synchronized block is used with the instance methods, each object gets its synchronized method. There will be only one thread for each object, that can be executed inside the method. If there is more than one object, then only one thread will be executed inside the block for each object.

 

See this code demonstration below:

1. public class myCounter {
2. private int counter = 0;
3. public synchronized void incrementCounter(int num) {
4. this.counter += num;
5. }
6. public synchronized void decrementCounter(int num) {
7. this.counter -= num;
8. }
9. }

2. Synchronized Static Methods

A Static method can also be marked as synchronized just like an instance method is marked using the synchronized keyword in Java.

 

Below is another code demonstration showing the working of a Java synchronized static method:

1. public static MyCounter {
2. private static int counter = 0;
3. public static synchronized void incrementCounter(int num) {
4. counter += num;
5. }
6. }

3. Declaring a Synchronized block inside Instance Methods

Instead of synchronizing the whole method, you can also just synchronize a particular block inside the method using the Java synchronized keyword.

 

See this synchronized block of Java code inside an unsynchronized Java method:

1. public void incrementCounter(int num) {
2. synchronized(this) {
3. this.counter += num;
4. }
5. }

4. A synchronized block inside the Static Method

A Synchronized blocks can also be used inside a static method.

 

Below is the code showing the use of a synchronized block inside the static method:

1. public class DemoClass {
2. public static void OutputMessage(String textMessage) {
3. synchronized(DemoClass.class) {
4. log.writeln(textMessage);
5. }
6. }
7. }

Why do we need Java synchronized keyword?

The Java synchronized keyword is extremely important as it is used for almost all activities related to multithreaded programming.

 

We also do not have any alternative for many of its notable features such as:

  • The Java synchronized keyword is the only way to make a block or a method synchronized.
  • The synchronized keyword in Java provides the feature of locking, which makes sure that no race condition could occur among threads. After getting locked, a thread can only read data from the main memory. After reading the data, it flushes the write operation and only then it can release the lock.
  • The synchronized keyword also helps in avoiding the reordering of the program statements.

Downsides of using Java synchronized keyword

It is certain that the synchronized keyword in Java is majorly responsible for concurrency in multithreaded applications but there are some very important points to be considered while using the Java synchronized keyword,

  • If you attempt to use a null object in a synchronized block then it is most likely that it will result in a NullPointerException.
  • While using the Java synchronized keyword, it is not allowed to use more than one JVM to provide access control to a shared resource.
  • The performance of the system can be significantly affected due to the slow working of the synchronized keyword.
  • If the synchronization is not properly implemented in your code, it could easily result in a deadlock or starvation so you must know enough before using the Java synchronized keyword.
  • It is illegal to use the Java synchronized keyword with the constructor in Java.
  • The Java synchronized keyword also cannot be used with the variables in Java.

Considering all these points, it might seem that using the Java synchronized keyword is not such a treat. Using it can be a bit tricky especially if you are new and not completely sure of know what you are doing.  Considering that, it is a better option to use the Java synchronized method instead of the Java synchronized keyword, at least until do not become good enough.

Conclusion

Multithreading is known for one of the most difficult areas of Java. It’s true. Concurrent programming is not very easy to learn but some decent understanding of multithreading and synchronization can be an excellent addition to your Java toolkit.

In this article, we discussed numerous ways of using the Java synchronized keyword to achieve synchronization in a multi-threaded application.

Related Article: How to use Java Generic Interface

We also covered every way of using the Java synchronized keyword with the aid of some examples. Guide to the Synchronized Keyword in Java

Author

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.

Write A Comment