Synchronization in JAVA

Synchronization in JAVA

Synchronization in java controls multiple threads from accessing the same shared resource in order to prevent an inconsistent state.

Java Synchronization is done when we want to allow only one thread to access the shared resource.

For example, let us say A and B are joint account holders of a bank, they both are at different locations and want to withdraw 1000$ each but their account has only 1000$, so now the software will lock one of the transactions and will wait for it to complete, let us say this transaction lock is of A, so as soon as A withdraws 1000$ the balance will be 0, and now B's transaction is executed but will show no balance left, else if it was not synchronized, it would have entered into an inconsistent state.

Synchronized Method

In the below program we will see how synchronized keyword is used as well as a synchronized method.

Program(Save as Main.java)

class threadSynchronization implements Runnable
{
    public void run()
    {
        criticalSection();
    }
    public synchronized void criticalSection()
    {
        String name = Thread.currentThread().getName();
        System.out.println(name+" has entered the Critical Section");
        for(int i=1;i<=3;i++)
            System.out.println("Name of Thread is "+name+" and Value = "+i); 
        System.out.println(name+" has exited the Critical Section!\n");
    }
}
class Main
{
    public static void main(String args[])
    {
        threadSynchronization ts = new threadSynchronization();
        Thread t1 = new Thread(ts); 
        Thread t2 = new Thread(ts);
        t1.start();
        t2.start();
    }
}

Output

Thread-0 has entered the Critical Section
Name of Thread is Thread-0 and Value = 1
Name of Thread is Thread-0 and Value = 2
Name of Thread is Thread-0 and Value = 3
Thread-0 has exited the Critical Section!

Thread-1 has entered the Critical Section
Name of Thread is Thread-1 and Value = 1
Name of Thread is Thread-1 and Value = 2
Name of Thread is Thread-1 and Value = 3
Thread-1 has exited the Critical Section!

From the above program we can see that, once Thread-0 enters the critical section, no other can enter the critical section till Thread-0 exits the critical section. This is only possible with help of synchronized keyword. If synchronization wasn't used, we would get a random output.

In the above example we have used a synchronized method.

Synchronized Block

If we only need to execute some lines of code and not all lines of code within a method, then we should synchronize only block of the code within which required instructions exists.

Synchronized block, syntax is :-

synchronized(object) {

code....}

where a thread can only enter once it has acquired the lock on object.

Example using a synchronized block

Program(Save as Main.java)

class threadSynchronization implements Runnable
{
    public void run()
    {
        int count = 0;
        synchronized(this)
        {
            String name = Thread.currentThread().getName();
            System.out.println(name+" has entered the Synchronized Block");
            for(int i=1 ;i<=3;i++)
                System.out.println("Count = "+(++count));
            System.out.println(name+" has exited the Synchronized Block\n");
       }
    }
}
class Main
{
    public static void main(String args[])
    {
        threadSynchronization ts = new threadSynchronization();
        Thread t1 = new Thread(ts); 
        Thread t2 = new Thread(ts);
        t1.start();
        t2.start();
    }
}

Output

Thread-0 has entered the Synchronized Block
Count = 1
Count = 2
Count = 3
Thread-0 has exited the Synchronized Block

Thread-1 has entered the Synchronized Block
Count = 1
Count = 2
Count = 3
Thread-1 has exited the Synchronized Block
Share Me!