×

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

SJF Scheduling Program in C

The SJF (shortest job first) or the shortest job next is the programming scheduling in the C. It is one of the CPU scheduling programming. The SJF is defined as...

4 minutes read.

Socket Programming in C

Socket programming is a process that connects the two or more nodes on a networking communication with respective to each other. One of the sockets that determines the socket (I.e.,...

5 minutes read.

fopen() function in C

fopen() function, is one of the file handling functions. It is used to open the existing file and perform operations on the file. If the file does not exist, it...

3 minutes read.

Structure in C

Why Structure came into the picture? In the actual world, we deal with entities that are collections of objects rather than tiny bits of data like integers, characters, floats, etc. So,...

4 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.

Fibonacci Series in C Using For Loop

In this C article, we will let you know about the procedure of displaying the Fibonacci series of the first “n” positive integers. The syntax of for loop used in the...

4 minutes read.

clrscr in C

clrscr function in C clrscr stands for: clr = clear scr= screen When the clrscr() function is called in a program everything currently displayed in the console(output of previous programs, output of current program,...

3 minutes read.

Conio.h in C

Header files are the source files with the extension of .h. In c language header files are referred to as the helping files and they contain definitions of various functions...

4 minutes read.

C Decision control statement

Decision Making C conditional statements are used to specify one or more conditions. The statements will be executed if the condition becomes true otherwise alternative statement will be executed if the...

3 minutes read.

fork() in C

Introduction To create a new function in the system, there is a need for a system call, i.e. fork system call. It is also known as the child process. These child...

2 minutes read.

Math functions in C

Math functions in C: In the C programming language, the compiler allows the developer to perform mathematical operations through the header’s functions, represented by <math.h>. The <math.h> header defines various mathematical...

3 minutes read.

Pyramid Pattern in C

Pyramid Pattern in C A pyramid is a polyhedron created by connecting a base that will be a polygon, and all the lateral faces are triangles. All the bases are connected...

5 minutes read.

Typedef vs define in C

Typedef VS define in C Typedef In the C programming language, a keyword called typedef can be used to give a type a new name. In other words, it is used to...

5 minutes read.

Tower of Hanoi in C

What is Tower of Hanoi? The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in...

4 minutes read.

Break, continue and goto statement in C

Break statement Break statement is used to break the process of a loop (while, do while and for) and switch case. Syntax: break; Example 1 while(test Expression) { // codes if(condition for break){ break; } // codes } Example 2 For(int it, condition,...

1 minute read.

C Function Argument and Return Values

Functions in the C programming language are declared to avoid repeatedly writing a performable block of code; it is the same in any programming language. When it comes to the...

3 minutes read.

What is String Comparison in C

String comparison is the process of comparing two strings (sequences of characters) to determine if they are equal, or if one is greater or less than the other. The comparison...

4 minutes read.

For Loop in C

The Syntax of For Loop for (initialization statement; test expression; update statement) {     /* main body of the FOR loop */ } How does For loop work? In for loop, the initialization command is...

3 minutes read.

Calloc in C

The calloc() is a library function in C which is used for memory allocation. The calloc() function dynamically allocates multiple blocks of memory to complex data structures. This includes data structures...

3 minutes read.

While-Loop in C

Syntax of While Loop The syntax that has been used for the while loop in C programming language is: while (termination condition) {   // the body of the loop  } Working of While-Loop Initially, we...

3 minutes read.