Static Synchronization in Java


Synchronization is a way that establishes cooperation between multiple threads trying to access shared resources. It is necessary for reliable thread interaction and is done using the ‘synchronized’ keyword. Here, threads are small sub processes of a big operation. In this article, we are going to learn static synchronization and how they manage threads so that they can work efficiently.

Multithreading and Static Synchronization

Multithreading

It is a feature of Java programming language that allows us to perform multiple operations simultaneously. In it, the operation gets divided into multiple smaller parts called a thread. Each thread performs one independent task without affecting the other thread’s performance. The main benefit of multithreading is the optimal use of resources like CPU and it boosts the execution time of allocated operations.

Synchronization

The threads are executed in an asynchronous manner therefore, it is impossible to predict how they are going to interact. Sometimes, several threads may try to access a single resource, then a problem arises because it might create a faulty result of the allocated task. At this time, Synchronization comes into the picture and ensures that a single thread can access the given resource at one time. This is possible because of the lock object that guards the synchronized region. When a thread enters that region, the lock gets assigned to it and it releases the lock after executing its task. Till the resources are busy other threads wait in a queue for their turn.

Static Synchronization: When we use this type of synchronization then, if a thread is in the static synchronized region, all other threads trying to access this region will be blocked. Since static methods belong to the class therefore, static synchronization applies class level lock.

Syntax

static synchronized returnType nameOfMethod( Type parameters) {
	// code
} 

returnType may be void or any primitive data type.

parameters contains name of the variable followed by datatype.

Program of Static Synchronization in Java

Working of Code

  • Create a class named ‘Thrd’ and inside it defines a static synchronized method named ‘operation()’ along with an argument.

  • Now, in this method, take a for loop that will run 4 times and increment the given argument. The try block of this loop will print the output with a specified time interval i.e. 1000 milliseconds.

  • Moving further, create three classes that extend ‘Thread’ class. Inside these classes pass the arguments to the ‘operation()’ method.

  • At last, in the main method create three objects for the thread class and execute them using the inbuilt method ‘start()’.

Example

class Thrd {
   static synchronized void operation(int data) {
      for(int i = 1; i <= 4; i++) {
         System.out.println(data++);   
         try {
            // each iteration performed with interval of 1 sec
            Thread.sleep(1000);   
         } catch(Exception exp){}   
      }
   }
}
class Thrd1 extends Thread {
   // thread number 1 
   public void run() {   
      Thrd.operation(1);   
   } 
}
class Thrd2 extends Thread {
   // thread number 2   
   public void run() {   
      Thrd.operation(5);   
   }
}
class Thrd3 extends Thread {
   // thread number 3
   public void run() {
      Thrd.operation(10);   
   }   
}   
public class ThrdExecution {
   public static void main(String args[]) {
      // creating object for thread class
      Thrd1 oprt1 = new Thrd1();   
      Thrd2 oprt2 = new Thrd2();  
      Thrd3 oprt3 = new Thrd3();
      // Starting the thread operation
      oprt1.start();   
      oprt2.start();  
      oprt3.start();
   }
}   

Output

1
2
3
4
10
11
12
13
5
6

We already discussed that we can’t predict the order of execution of the thread. In the above output, the first thread was executed first then, third and then second. We will get different outputs each time when we run the code.

Conclusion

In this article, we have discussed one of the most important topics of multithreading. The synchronization guarantees that only one thread can execute the operation at a given time means it pushes the threads to execute blocks of code sequentially.

Updated on: 15-May-2023

444 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements