Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Synchronization Examples
Next article icon

Static Synchronization in Java

Last Updated : 25 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Synchronization is the potential to regulate the access of multiple threads to any shared resource. Synchronization in Java is essential for reliable communication between threads. It is achieved in Java with the use of synchronized keywords.

Important Points Regarding Synchronization

  • It is only for methods that are at the Object level.
  • If a method or block is synchronized, then it requires an object-level lock to start execution.
  • Synchronization is the most dangerous word in Java because this is the only reason for the deadlock.
  • Use synchronized keywords when it is required and try to use synchronized blocks.

Static Synchronization

The Synchronized method may lose its behaviour of getting an ordered output. When there are more objects of a class, It acquires only the lock of the particular instance. To maintain the Synchronized behavior, we need a class-level lock rather than an instance-level lock which can be achieved by Static Synchronization.

Static Synchronized method is also a method of synchronizing a method in Java such that no two threads can act simultaneously static upon the synchronized method. The only difference is by using Static Synchronized. We are attaining a class-level lock such that only one thread will operate on the method. The Thread will acquire a class-level lock of a Java class, such that only one thread can act on the static synchronized method.

Syntax:

synchronized static return type class name{}

Note: When a class has both synchronized and static synchronized methods they can run parallelly ,as those two methods require different locks.

Let us assume that there are 6 threads. The order of execution will be

Example - 6 Threads in Java

Threads and Classes

Here t1,t2... t6 are the thread names

The complete declarations of  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()
  1. t1.method1() starts execution as it attains class level lock of Manager class.
  2. t2.method1() wait for its time to start execution, as it is a static synchronized method, it requires a class level lock,  as t1 has already acquired class level lock t2 must wait until t1 execution.
  3. t3.method2() waits as it requires class level lock, so it must wait until t1 releases the lock.
  4. t4.method3() starts execution as it is static methods requires no lock
  5. t5.method4() starts execution as it is instance or(normal) level synchronized method and requires object level lock, so it attains object level lock.
  6. t6.method5() starts execution as it is an instance method or a normal method

Example: Below is an example program of multithreading with static synchronized

Java
// Java program of multithreading  // with static synchronized  class Display {     public static synchronized void wish(String name)     {         for(int i=0;i<3;i++)         {             System.out.print("Good Morning: ");             System.out.println(name);             try{                 Thread.sleep(2000);             }             catch(InterruptedException e)             {             }         }     } }  class MyThread extends Thread{     Display d;     String name;     MyThread(Display d,String name)     {         this.d=d;         this.name=name;     }     public void run()     {         d.wish(name);     } }  class Main{     public static void main(String arg[])     {         Display d1=new Display();         Display d2=new Display();         MyThread t1=new MyThread(d1,"Dhoni");         MyThread t2=new MyThread(d2,"Yuvaraj");         t1.start();         t2.start();     } } 

Note: Each wish will be printed after a gap of 2000 ms.

Output

First time of execution:
Good Morning: Dhoni
Good Morning: Dhoni
Good Morning: Dhoni
Good Morning: Yuvaraj
Good Morning: Yuvaraj
Good Morning: Yuvaraj

Second time of execution:
Good Morning: Yuvaraj
Good Morning: Yuvaraj
Good Morning: Yuvaraj
Good Morning: Dhoni
Good Morning: Dhoni
Good Morning: Dhoni

Explanation of the above Program:

In the above program, three classes, namely Display, MyThread, and Main, are defined where each class has -  

  1. class Display: The code which needs for the child thread to run
  2. class MyThread: The purpose of this class is to extend class Thread and to allocate value names, and call the wish method of class Display
  3. class Main: It is the main class of the whole program, and it creates a child thread

The control flow:

As we know, the execution of the program starts with the main method. First, we create two child threads and assign them to the display objects for the threads, and after t2.start(), there will be three threads, namely(main,t1,t2), and the execution procedure is as follows.

The child threads start their execution t1, and as the wish method is static synchronized, the thread t1 gains the class level lock of class Display and starts executing the wish method. If the next thread comes, it must wait until the execution of the previous thread to attain the class level lock.

Note: We can't say the exact order of output. As a programmer, we cannot say which thread starts its execution or the order of execution ,they are not in the hands of a programmer it is the job of Thread schedular.

Difference between Synchronized and Static Synchronized in Java

 SynchronizedStatic Synchronized
It requires an object-level lock.It requires a class-level lock.
Its method need not be declared static.Its method needs to be declared static.
It is used regularly.It is not used regularly.
 A different instance is created for each object.Only one instance for the entire program.

Next Article
Synchronization Examples
author
srivathsanani
Improve
Article Tags :
  • Java
  • Java-Object Oriented
Practice Tags :
  • Java

Similar Reads

  • Synchronization of ArrayList in Java
    Implementation of ArrayList is not synchronized by default. It means if a thread modifies it structurally and multiple threads access it concurrently, it must be synchronized externally. Structural modification implies the addition or deletion of element(s) from the list or explicitly resizes the ba
    4 min read
  • Java Method and Block Synchronization
    In Java, Synchronization is very important in concurrent programming when multiple threads need to access shared resources. Java Synchronization can be applied to methods and blocks. Method synchronization in Java locks the entire method and Block synchronization locks only a specific section of the
    7 min read
  • Static Variables in Java
    In Java, when a variable is declared with the static keyword. Then, a single variable is created and shared among all the objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable. These are the main scenarios when we u
    3 min read
  • Using Static Variables in Java
    Here we will discuss the static variables in java. Java actually doesn’t have the concept of Global variable. To define a Global variable in java, the keyword static is used. The advantage of the static variable is discussed below. Now geeks you must be wondering out what are the advantages of stati
    3 min read
  • Synchronization Examples
    The Synchronization is an important concept in operating systems that ensures the smooth and coordinated execution of processes and threads. It is the task of coordinating the execution of processes in such a way that no two processes can access the same shared data and resource. It is a critical pa
    6 min read
  • Importance of Thread Synchronization in Java
    Thread synchronization in Java is important for managing shared resources in a multithreaded environment. It ensures that only one thread can access a shared resource at a time, which enhances the overall system performance and prevents race conditions and data corruption. Why is Thread Synchronizat
    8 min read
  • Java Lock Framework vs Thread Synchronization
    In Java, thread synchronization is achieved using the Lock framework which is present in the java.util.concurrent package. Synchronization ensures that only one thread can access a resource at a time by preventing issues like data corruption or inconsistency. Java offers two primary mechanisms for a
    4 min read
  • Final Static Variable in Java
    When the value of a variable is not varied, then it is not a good choice to go for an instance variable. At that time, we can add a static modifier to that variable. Whenever we declare a variable as static, then at the class level, a single variable is created which is shared with the objects. Any
    3 min read
  • Java notify() Method in Threads Synchronization with Examples
    The notify() method is defined in the Object class, which is Java's top-level class. It's used to wake up only one thread that's waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread. If multiple threads are waiting for noti
    3 min read
  • Synchronization in Android with Example
    In Android, synchronization refers to the process of ensuring that data stored in multiple locations is the same and up-to-date. This can be achieved through various methods such as using the built-in Android synchronization adapters, or by manually implementing synchronization using the Android Syn
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences