Java Thread synchronization

Thread synchronization

 

Synchronization is used to avoid deadlocks in multithreaded environment by managing access to shared resources.

 

In synchronized code, once one thread has picked up the lock, no other thread can enter the synchronized code until the first thread releases the lock.

 

Monitor is a term referred to the object that is being locked.

 

Here are some key points about synchronization :

 

– Only methods or blocks of code can be synchronized. Variables and classes can not be synchronized.

– If two threads are about to enter a synchronized method/block, only one thread can execute the method/block at a time, the other has to wait until the lock has been released by first thread.

– If a thread goes to sleep, it doesn’t release the locks.

– Static methods can be synchronized using a class level lock.

Synchronization at method level:

 

just add synchronized to the method signature :

 

  public synchronized void somemethod(){
    System.out.println("synchronized method");
  }

 

Similarly for static method too, just adding synchronized to the static method signature would work

 

public static synchronized void somemethod(){
    System.out.println("synchronized method");
  }

 

Synchronization on a code block

 

To synchronize a block of code, specify which object’s lock is being used for the lock.

 

public void somemethod(){
    synchronized(this){
    System.out.println("synchronized block");
    }
  }

 

Here is how to write the same code for synchronization within a static method:

 

  public static void somemethod(){
    try {
      Class c1 = Class.forName("HelloThread.class");
      synchronized(c1){
        System.out.println("synchronized method");
        }
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    
  }

© 2015 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags