Synchronized block

Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 100 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.
 

Block synchronization in java is preferred over method synchronization in java because by using block synchronization you only need to lock the critical section of code instead of whole method.

If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.
Points to remember for Synchronized block

  1. Synchronized block is used to lock an object for any shared resource.
  2. Scope of synchronized block is smaller than the method.

Syntax to use synchronized block

synchronized (object reference expression) { 
   //code block 
 }

Example of synchronized block:
Let's see the simple example of synchronized block.
class First
{
   public synchronized void display(String msg) 
   {
      System.out.print ("["+msg);
      try
      {
         Thread.sleep(500); 
      }
      catch(InterruptedException e)
      {
         e.printStackTrace();
      }
      System.out.println ("]");
   }
}

class Second extends Thread
{
     String msg;
     First fobj;
     Second (First fp,String str)
     {
        fobj = fp;
        msg = str;
        start();
     }
     public void run()
     {   
        synchronized(fobj){         //synchronized block
            fobj.display(msg);
         }
     }
}

public class SyncBlockDemo
{
    public static void main (String[] args) 
    {
       First fnew = new First();
       Second ss  = new Second(fnew, "welcome");
       Second ss1 = new Second (fnew,"to");
       Second ss2 = new Second(fnew, "dineshonjava.com");
    }
}

output:




<<Previous <<   || Index ||   >>Next >>

No comments:

Post a Comment