Table of contents
1.
Introduction 
2.
Static Synchronisation
3.
Example
3.1.
Threads
3.2.
Methods
3.3.
Program
3.4.
Output
3.5.
Classes
3.6.
Control Flow
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Static Synchronisation in Java

Author Pankhuri Goel
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

Synchronisation is the ability to control different threads' access to a shared resource. In Java, synchronisation is required for thread communication to be reliable. Synchronised keywords are used in Java to achieve this.

The Synchronised method's behaviour of returning an ordered output may be lost. When there are multiple objects of the same class, it only gets the lock of the specific instance. We require a class-level lock rather than an instance-level lock to keep the Synchronised functionality, which Static Synchronisation can provide.

You can also read about the Multiple Inheritance in Java.

Static Synchronisation

In Java, a static synchronised method is also a technique of synchronising a method so that no two threads can act on the synchronised method simultaneously. The only change is that Static Synchronised is used. We're achieving a class-level lock, which means that only one thread can use the method. The Thread class will obtain a class level lock of a java class, allowing only one thread to interact with the static synchronised method.

Syntax: synchronized static return type class name{}

 

Must Read Static Blocks In Java.

Example

Let us assume that there are six threads. The following will be the order of execution:

Threads

Here, we take six threads, namely, t1, t2, t3, t4, t5 and t6.

Methods

The complete declarations of the various methods are:

method1: public static synchronized void method1()

method2: public static synchronized void method2()

method3: public static void method3()

method4: public synchronized int method4()

method5: public String method5()

 

The execution flow of the method will be like this: 

  • When t1.method1() obtains class level lock of the Manager class, it begins execution.
  • Because it is a static synchronised method, t2.method2() must wait for its time to begin execution. Because t1 has already obtained the class level lock, t2 must wait till t1 executes.
  • t3.method2() must wait until t1 releases the lock because it requires a class level lock.
  • t4.method3() begins execution immediately because it is a static method that does not require a lock.
  • Because t5.method4() is an instance (or normal) level synchronised method that requires object level lock, it obtains object level lock.
  • t6.method5() executes as an instance method or as a regular method.

 

An example of a multithreading programme with static synchronisation is shown below.

Program

class Display
{
    public static synchronized void wish(String name)
    {
        for(int i=1;i<=5;i++)
        {
            System.out.print("Hello! Good Morning: ");
            System.out.println(name);
            try{
                Thread.sleep(500);
            }
            catch(InterruptedException e)
            {
            }
        }
    }
}
  
class MyThread extends Thread
{
    Display dis;
    String name;
    MyThread(Display dis,String name)
    {
        this.dis=dis;
        this.name=name;
    }
    public void run()
    {
        dis.wish(name);
    }
}
  
class Main
{
    public static void main(String arg[])
    {
        Display d1=new Display();
        Display d2=new Display();
        MyThread t1=new MyThread(d1,"Anushka");
        MyThread t2=new MyThread(d2,"Tara");
        t1.start();
        t2.start();
    }
}

Output

Note that each execution of the wish method is at an interval of 500ms.

Classes

Three classes, Display, MyThread, and Main, are defined in the preceding programme, with each class having:

class Display: The code that must be executed for the child thread to run.

class MyThread: The objective of this class is to extend class Thread and allocate value names, as well as to call the Display class's wish method.

class Main: This is the program's main class, and it produces a child thread.

Control Flow

The main method is where the programme begins to run. First, we construct two child threads and assign them to the threads' display objects; then, after t2.start(), there will be three threads (main,t1,t2), with the following execution procedure.

Because the wish method is static synchronised, the thread t1 gets the class level lock of class Display and begins executing the wish method. If the next thread arrives, it must wait for the previous thread to complete its execution before gaining the class level lock.

Do note that we are unable to specify the output order. As a programmer, we have no control over when a thread begins to execute or in what order it runs; this is the duty of the Thread Scheduler.

Practice it on online java compiler for better understanding.

Related Topic: Multithreading in C#

FAQs

  1. Give some features of synchronisation.
    Some basic features of synchronisation are as follows: 
    → It only applies to methods at the Object level.
    → If a method or block is synchronised, it must first get an object-level lock before it can begin to execute.
    → The most deadly word in Java is synchronisation because it is the only reason for the deadlock.
    → When possible, utilise synchronised keywords instead of synchronised blocks.
     
  2. What is the difference between synchronisation and static synchronisation?
    The difference between Synchronisation and Static Synchronisation is as follows:

     
  3. What is a class level lock?
    A lock is a Java interface that is part of the Java.util.concurrent.locks package. Java locks work in a similar way to synchronised blocks in terms of thread synchronisation. A new locking mechanism was added after some time. Compared to the Synchronised block, it is more flexible and offers more options.

    In Java, each class has its own lock, known as a class level lock. A class level lock is required if a thread wishes to run a static synchronised method. A class level lock prohibits multiple threads from entering a synchronised block in any of the class's available instances on runtime. This means that if a class has ten instances at runtime, only one thread will be able to access each instance's one method or block at a time. When the method is finished, the thread automatically releases the lock. If you wish to protect static data, you should use it.
     
  4. What is multithreading?
    Multithreading is a Java feature that permits the execution of two or more portions of a programme at the same time to maximise CPU efficiency. Thread is the name given to each component of such a programme. Threads are hence lightweight processes within processes. It's typically utilised in video games and animation.

Key Takeaways

In this article, we learned about static synchronisation in Java. Through an example, we learned about its implementation and working. 

Check out this article - Upcasting and Downcasting in Java

We hope this blog has helped you enhance your knowledge. If you want to learn more, check out our articles on Multithreading in Python, Multithreading in Java - Coding Ninjas Coding Ninjas StudioLock Variable Synchronization - Coding Ninjas Coding Ninjas Studio and Two-Phase Locking Protocol - Coding Ninjas Coding Ninjas Studio. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences, and much more!

Happy Reading!

Live masterclass