×

Limitations of Synchronisation and Uses of Static Synchronisation in Multithreading

The multithreading component of java is the element around which the idea rotates as it permits simultaneous execution of at least two program pieces for the most significant usage of a central processor. Each piece of such a program is known as a string. In this way, strings are lightweight cycles inside a cycle, whereas we as a whole realise strings can be made by involving two systems as recorded:

  • Extending the Thread class
  • Implementing the Runnable Interface

On the off chance that numerous strings access a solitary asset at a time, there exists a possibility of information hustling or terrible result. Allow us to grasp this with the assistance of a story. Let us take the case of information hustling in multithreading to see the constraints of synchronisation and the purposes of static synchronisation.

Thread Creation by Extending Thread Class

We make a class that expands java.lang.Thread class. This class supersedes the run() strategy accessible in the String class. A string starts its life inside the run() technique. We make an object of our new class and call the start() technique to begin the execution of a string. Begin() summons the run() strategy on the String object.

Example:

// Java program for thread creation by implementing the Runnable Interface
class MTD implements Thread {
    public void run()
    {
        try {
            //here, we are displaying the thread that is running
            System.out.println("The Thread " + Thread.currentThread().getId() + " is running successfully");
        }
        catch (Exception e) {
            //here, if there are any exceptions, we will throw it
            System.out.println("Exception is raised successfully");
        }
    }
}
 
//here, we are declaring the Main Class
class MT {
    public static void main(String[] args)
    {
        int a = 8; //here, we are declaring the number of threads
        for (int i = 0; i < n; i++) 
{
            		Thread obj = new Thread(new MTD());
            		obj.start();
        	}
    }
}

Output:

Thread 3 is running successfully
Thread 1 is running successfully
Thread 2 is running successfully
Thread 5 is running successfully
Thread 4 is running successfully
Thread 8 is running successfully
Thread 7 is running successfully
Thread 6 is running successfully

Thread Creation by Implementing Runnable Interface:

We make another class which carries out java.lang.Runnable connection point and supersede run() strategy. Then we launch a String item and call start() technique on this article.

Example:

// Java program for thread creation by implementing the Runnable Interface
class MTD implements Runnable {
    public void run()
    {
        try {
            //here, we are displaying the thread that is running
            System.out.println("The Thread " + Thread.currentThread().getId() + " is running successfully");
        }
        catch (Exception e) {
            //here, if there are any exceptions, we will throw it
            System.out.println("Exception is raised successfully");
        }
    }
}
 
//here, we are declaring the Main Class
class MT {
    public static void main(String[] args)
    {
        int a = 8; //here, we are declaring the number of threads
        for (int i = 0; i < n; i++) 
{
            		Thread obj = new Thread(new MTD());
            		obj.start();
        	}
    }
}

Output:

Thread 3 is running successfully
Thread 1 is running successfully
Thread 2 is running successfully
Thread 5 is running successfully
Thread 4 is running successfully
Thread 8 is running successfully
Thread 7 is running successfully
Thread 6 is running successfully

Implementation of Data Racing in Multithreading:

//simple Java program to show Data racing in multithreading. 
//here, we are declaring the helper class 1
class book {
    int t = 1;
    //here, we are declaring the method to book a train ticket
    void book(int request, String name)
    {
        //here, we are writing the logic to book the ticket
        if (t >= request) {
            System.out.println(name + " booked " + request + " ticket.");
            t = t - 1;
            System.out.println("The Tickets left are: " + t);
        }
        else {
            System.out.println("No tickets are available.");
        }
    }
}
//here, we are writing Helper class 2, which extends the Thread class.
//here, the book method is called from this class using the object
//that is passed from the main class.
class MT extends Thread {
    book ob;
    int n;
    String nam;
    MT(book ob, String nam, int n)
    {
        this.ob = ob;
        this.n = n;
        this.nam = nam;
    }
//here, we are running the threads
    public void run() { ob.book(n, nam); }
}
//here, we are declaring the Driver class
public class TR {
    //here, we are declaring the Driver method
    public static void main(String[] args)
    {
        // Creating the object "ob" of the book class and passing it to the MT class
        book ob = new book();
        MT t1 = new MT(ob, "Vijay Kumar", 1);
        MT t2 = new MT(ob, "Ajay Kumar", 1);
        // When a program calls the start() method, a new thread is created and then //the run() method is executed.
        //here, we are Starting threads created above
        t1.start();
        t2.start();
    }
}

Output:

Vijay Kumar booked 1 ticket.
Ajay Kumar booked 1 ticket.
The Tickets left are: 0
The Tickets left are: -1

Synchronization:

Synchronisation in java is the capacity to control the entrance of various strings to any common asset. In the Multithreading idea, numerous strings attempt to get to the common assets all at once to deliver conflicting outcomes. Synchronization is essential for solid correspondence between strings.

Synchronisation Component created by involving the synchronised catchphrase in java language. It is based on top of the locking instrument; this locking component is dealt with by Java Virtual Machine (JVM). The synchronised catchphrase is just material for strategies and blocks; it can't make a difference to classes and factors. The synchronised watchword in java makes a block of code known as an essential segment. To go into the basic segment string requirements to acquire the comparing item's lock.

Why we have to use Synchronization:

  • Synchronization assists in forestalling stringing impedance.
  • Synchronization assists with forestalling simultaneousness issues.

For the above example, we give a lock to the item and proclaim a delicate area(withdraw strategy). An object can have various strings; however, the touchy region must be gotten to by 1 string at a time.

Example:

//simple Java program to show Data racing in multithreading using Synchronization.
//here, we are declaring the helper class 1
class book {
    int t = 1;
    //here, we are declaring the method to book a train ticket
    synchronized void book(int request, String name)
    {
        //here, we are writing the logic to book the ticket
        if (t >= request) {
            System.out.println(name + " booked " + request + " ticket.");
            t = t - 1;
            System.out.println("The Tickets left are: " + t);
        }
        else {
            System.out.println("No tickets are available.");
        }
    }
}
//here, we are writing Helper class 2, which extends the Thread class.
//here, the book method is called from this class using the object
//that is passed from the main class.
class MT extends Thread {
    book ob;
    int n;
    String nam;
    MT(book ob, String nam, int n)
    {
        this.ob = ob;
        this.n = n;
        this.nam = nam;
    }
//here, we are running the threads
    public void run() { ob.book(n, nam); }
}
//here, we are declaring the Driver class
public class TR {
    //here, we are declaring the Driver method
    public static void main(String[] args)
    {
        // Creating the object "ob" of the book class and passing it to the MT class
        book ob = new book();
        MT t1 = new MT(ob, "Vijay Kumar", 1);
        MT t2 = new MT(ob, "Ajay Kumar", 1);
        // When a program calls the start() method, a new thread is created and then //the run() method is executed.
        //here, we are Starting threads created above
        t1.start();
        t2.start();
    }
}

Output:

Vijay Kumar booked 1 ticket.
The Tickets left are: 0
No tickets are available.

Limitations of Synchronization:

Assuming we have various strings from 1 item, synchronisation will deal with the information hustling or terrible result. What will occur assuming that different strings are allocated from multiple objects? This will again bring about awful results or data hustling.

Example:

//synchronization when multiple threads get assigned from various objects.
//simple Java program to show Data racing in multithreading using Synchronization.
//here, we are declaring the helper class 1
class book {
    int t = 1;
    //here, we are declaring the method to book a train ticket
    synchronized void book(int request, String name)
    {
        //here, we are writing the logic to book the ticket
        if (t >= request) {
            System.out.println(name + " booked " + request + " ticket.");
            t = t - 1;
            System.out.println("The Tickets left are: " + t);
        }
        else {
            System.out.println(name+"No tickets are available.");
        }
    }
}
//here, we are writing Helper class 2, which extends the Thread class.
//here, the book method is called from this class using the object
//that is passed from the main class.
class MT extends Thread {
    book ob;
    int n;
    String nam;
    MT(book ob, String nam, int n)
    {
        this.ob = ob;
        this.n = n;
        this.nam = nam;
    }
//here, we are running the threads
    public void run() { ob.book(n, nam); }
}
//here, we are declaring the Driver class
public class TR {
    //here, we are declaring the Driver method
    public static void main(String[] args)
    {
        // Creating the object "ob" of the book class and passing it to the MT class
        book ob1 = new book();
        book ob2 = new book();
        MT t1 = new MT(ob1, "Vijay Kumar", 1);
        MT t2 = new MT(ob2, "Ajay Kumar", 1);
        // When a program calls the start() method, a new thread is created and then //the run() method is executed.
        //here, we are Starting threads created above
        t1.start();
        t2.start();
    }
}

Output:

Vijay Kumar booked 1 ticket.
Ajay Kumar booked 1 ticket.
The Tickets left are: 0
The Tickets left are: -1

We have simply 1 ticket, yet because of data racing, the two of them are booked effectively! To deal with this issue we want to concentrate on static synchronization.

Static Synchronization:

The Synchronized strategy might lose its way of behaving of getting an arranged result. At the point when there are more objects of a class, It procures just the lock of the specific case. To keep up with the Synchronized way of behaving, we want a class-level lock instead of an occurrence-level lock which can be accomplished by Static Synchronization.

Static Synchronized strategy is likewise a technique for synchronising a strategy in java with the end goal that no two strings can act at the same time static upon the synchronised technique. The main distinction is by utilising Static Synchronized. We are accomplishing a class-level lock with the end goal that only one string will work on the method. The String will procure a class-level lock of a java class, with the end goal that only one string can follow up on the static synchronized technique.

Example:

//synchronization when multiple threads get assigned from various objects.
//simple Java program to show Data racing in multithreading using static //Synchronization.
//here, we are declaring the helper class 1
class book {
    static int t = 1;
    //here, we are declaring the method to book a train ticket
    static synchronized void book (int request, String name)
    {
        //here, we are writing the logic to book the ticket
        if (t >= request) {
            System.out.println(name + " booked " + request + " ticket.");
            t = t - 1;
            System.out.println("The Tickets left are: " + t);
        }
        else {
            System.out.println(name+"No tickets are available.");
        }
    }
}
//here, we are writing Helper class 2, which extends the Thread class.
//here, the book method is called from this class using the object
//that is passed from the main class.
class MT extends Thread {
    book ob;
    int n;
    String nam;
    MT(book ob, String nam, int n)
    {
        this.ob = ob;
        this.n = n;
        this.nam = nam;
    }
//here, we are running the threads
    public void run() { ob.book(n, nam); }
}
//here, we are declaring the Driver class
public class TR {
    //here, we are declaring the Driver method
    public static void main(String[] args)
    {
        // Creating the object "ob" of the book class and passing it to the MT class
        book ob1 = new book();
        book ob2 = new book();
        MT t1 = new MT(ob1, "Vijay Kumar", 1);
        MT t2 = new MT(ob2, "Ajay Kumar", 1);
        // When a program calls the start() method, a new thread is created and then //the run() method is executed.
        //here, we are Starting threads created above
        t1.start();
        t2.start();
    }
}

Output:

Vijay Kumar booked 1 ticket.
The Tickets left are: 0
Ajay Kumar, No tickets are available.

Conclusion:

At the point when we have different strings from a solitary item, then we can utilise synchronisation to lock the item to pass 1 string at a time and prevent terrible results.

In the event that different strings are allocated from various articles, we can not utilise synchronisation. In such cases giving a lock to the item will bring about information hustling. We want to use static synchronisation and provide certainty to the class. The class will choose 1 one thing at a time. An article like this will pick 1 string and pass it to the temperate region.


Related Topics

How to use sine() function in C

What is Function? The function is a set of statements. It takes input and performs some computation to produce output. The process is a set of codes only achieved when it is...

3 minutes read.

Nested Structure in C

In C language, we can create nested Structure (Structure within Structure). There are two ways to define a nested structure. By separate structure By Embedded structure   Separate structure In a separate...

1 minute read.

C vs Java Strings

String in C In C, we can define a string as a bunch of characters. A character array is distinguished from a string by the presence of the special character '\0'...

5 minutes read.

Long int in C

We use data type to avoid the type of data to be stored for a variable at the time of declaration.So, we can say that the variable type is known...

3 minutes read.

What is 2s Complement in C?

The complement of 2s in C is generated from the 1s in C. As we know, the 1s complement of a binary number is generated by converting bit 1 to...

4 minutes read.

Dynamic memory allocation

Dynamic memory allocation is used to allocate the memory at runtime. It has following function within <stdlib.h> header file. Function Syntax malloc() malloc (number *sizeof(int)); calloc() calloc (number, sizeof(int)); realloc() realloc (pointer_name, number * sizeof(int)); free() free (pointer_name); malloc() function The process...

2 minutes read.

OpenGL in C

OpenGL stands for Open Graphics Library. It is a low-level, widely supported modeling and rendering software package that is widely available across all the platforms. It is an API used...

4 minutes read.

Positioning of file in C

Positioning() function in c The fseek() function is utilized to change the document position of the stream . The fully extent of value from the source should be one of the...

3 minutes read.

Results of Comparison Operations in C and C++

In this tutorial, we will explore comparison operators and how the system should compare an incoming value supplied as a context parameter to a given value or range of values. A...

2 minutes read.

Consumer billing system in C

Introduction : Billing has always been taught to do perfectly, we know today's world is full of products, and We all are using multiple products. We are buying and selling various...

9 minutes read.

Ceil and Floor in C

In arithmetic, a rational number is a number that can be expressed as the quotient p/q of two integers. Where q is zero. The set of rational numbers includes all...

6 minutes read.

Git Hooks

Git Hooks Overview Just like other version control systems, Git has its way to deliver customized scripts whenever some important activity occurs. The hooks act just like the triggers or catalysts...

4 minutes read.

For Loop in C Programming Examples

The Syntax of the For Loop for (initialization statement; termination condition; modifying (increment/ decrement) statement) {       /* main body of the For loop */     } In for loop, the initialization command...

6 minutes read.

Fseek Function in C

The fseek function is a function in the C standard library that changes the position of the file pointer in a stream-oriented file. It is typically used to move the...

3 minutes read.

Big O Notation in C

Big O Notation in C: In the C programming language, we have so many algorithms and solutions to the problems that exist, which have different aspects and purposes to an...

3 minutes read.

Unformatted input() and output() function in C

Unformatted Input and Output functions take the character, character array, and strings as input. We can read-only character data types with these functions. These functions are already defined in the...

5 minutes read.

What is a buffer in C?

A buffer is an area of memory set aside for the temporary storage of data. A data buffer (or just buffer) is a region of a physical memory storage used to...

5 minutes read.

Ferror() in c

Ferror():  In C, the ferror() function checks assuming there is a blunder in the given stream. The ferror() function is utilized to check for the document blunder on given stream. A return...

4 minutes read.

Else If Ladder in C

What is Else If Ladder: When there are multiple options and a user has to decide from the options, we use Else If Ladder. Basically, it is an extension of if...

3 minutes read.

Pi() Function in C

Pi: Mathematic constants are not defined in the c or c++ programming languages. To use the Mathematical constants firstly, we have to define the _USE_MATH_DEFINES and then declare the cmath and...

3 minutes read.