eagertoLearn
eagertoLearn

Reputation: 10162

Synchronization of methods, objects, class in Java

I need some clarification with regards to use of synchronization in multi-threaded environment. I have a small example Class below. but I am actually finding it hard to make a test case of how the following will work; The reason I want test case is to the understand how synchronization handles these different scenarios


Some tips on on how to create two threads that act on same object and same method will be helpful (I understand I need to extend Thread class or implement Runnable interface). But not sure how to make a two threads call the same method on same object.

class SharedResource {
     public Integer x =0;
     public static Integer y=0;
     Object dummy = new Object();
     public Integer z=0;

     public synchronized static void staticMethod(){
         System.out.println("static Method is called");
         y++; 
     }

     public synchronized void incrementX(){
         System.out.println("instance method; incrementX");
         x++;
     }

     public void incrementXBlock(){
         synchronized(this){
             x++;
         }
         System.out.println("instance method; incrementXBlock");
     }

     public void incrementZ(){
         synchronized (dummy) {
             z++;
         } 
         System.out.println("synchronized on dummy; incrementZ method ");
     }
}

public class ThreadSynchronization extends Thread {

}

I have read these posts, but I am not positive if I understood it clearly.

Java synchronized method lock on object, or method?, Does java monitor include instance variables?

Upvotes: 6

Views: 1226

Answers (1)

Holger
Holger

Reputation: 298539

class SharedResource {
  public synchronized static void staticMethod(){
    System.out.println("static Method is called");
    y++; 
  }
  public synchronized void incrementX(){
     System.out.println("instance method; incrementX");
     x++;
  }
}

does the same as

class SharedResource {
  public static void staticMethod(){
    synchronized(SharedResource.class) {
      System.out.println("static Method is called");
      y++;
    }
  }
  public void incrementX(){
    synchronized(this) {
      System.out.println("instance method; incrementX");
      x++;
    }
  }
}

Simply said, a thread entering a synchronized block will acquire a lock on the specified object for the duration of the block. This implies that at most one thread can execute a synchronized code block for a particular lock object. Since the Class instance and a particular instance of that class are different object, synchronized static methods and synchronized instance methods do not block each other. But there is no difference between “method level” and “block level”; the important point is which object is chosen for the synchronization.

Upvotes: 4

Related Questions