Mystery of Synchronized Keyword

'Synchronized' keyword is used to ensure that only one thread access a code block or a method at a time. It is very important keyword in multi-threaded programming. In multi-threaded programming, multiple threads work on the same code blocks simultaneously. But there can be some code blocks which manipulate shared data. So if multiple threads executes the same code and try to manipulate the same data, it can results in inconsistent result. For example:

public class TestSynchronized {

private int i;

// suppose param value is 5
public void testMethod( int param)
{
    // thread update i to 5
    // simultaneously other thread enters the block and update i to 10 before first thread would be able to            
    // execute next statement
    i = i + param;

    // result is expected to be 25
    // but result comes to 50, as second thread updates i to 10 before first thread executes the multiple
    //statement

    int result = i*5;

    System.println.out("thread[" + Thread.currentThread + "] result[" + result  + "]");
    i = 0;
}

}



So here the solution is to synchronize the method using synchronize keyword. Synchronize keyword helps to ensure that only one thread access the testMethod and if there is another thread which wants to execute the testMethod, it will be put to wait. Hence it will help to avoid the above mentioned criteria where simultaneous access by two threads results in inconsistent data.

So Synchronize keyword is like a gatekeeper of a room, who allows only one entry at a time and hence ensure that only one person should be there in room at a time. As soon as the first person leave the room, gatekeeper allows the next person in queue to enter the room.

Synchronize keyword can be used in two ways. We can either use 'Synchronize' keyword with method statement itself.It will synchronize the access to whole code written in method. Example:

public synchronized void testMethod()

Other way is to make a specific code block as synchronized, like


public void testMethod()
{
    synchronized (this)
    {
        i = i + param;
    } 
    int result = i*5;
    System.println.out("thread[" + Thread.currentThread + "] result[" + result  + "]");
    i = 0;
}

Now there is a difference between synchronized keyword used with method and with specific code block.Synchronized code is always slow in execution, reason is that as only one thread can access the code at a time so program can not benefit the parallel execution of threads for this code block. Every thread wait for previous thread to complete its work. Hence this overall process slow down the execution. So it is very important to use synchronized keyword carefully only for the code which actually needs synchronization. Like in above example, we synchronize only one line which should not be exposed to parallel execution. 

A simple example is like multiple painters are working to paint a house. Every painter is having specific work like to paint the wall, and to paint the windows so on. We want that only one painter go for a single wall at a time, either to paint the wall or to pain the window so that their work won't interfere with each other. Hence  we make every painter to first take a lock for the work say on the wall and then proceed for the work. So it will make sure that only one painter will get access to the wall at a time and hence do his work. This way both the work will be executed in a sequence and work of both the painters won't interfere with each other. 

The other question is that how Synchronized keyword actually works and how it lock the access to the code block. This is explained in another blog post 'Simplifying the Locking Mechanism in Threads'

People who read this post also read :



2 comments:

Saurabh Dixit said...

Good description of synchronized keyword and really nice Painter example for understand Synchronize

research help said...

Many institutions limit access to their online information. Making this information available will be an asset to all.

Post a Comment