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
If a
threadcallsSharedResource.staticMethod, it will acquire thelockfor theclass.does it mean aninstanceofSharedResource, say x, will have to wait till it getslockto exectutex.staticMethod.Will
synchronizationofthisin ablock, acquires the lock for that section of the code or for entireobject. i.e can anotherthreadcall the samemethodon sameobject; but execute the remainder of the code that is not part ofsynchronization blockIf the above point is true, having a
dummy objecttolockon does not provide any additional benefit. Correct?So there are different levels of
synchronziations.Classlevel,Objectlevel,methodlevel andblock level. so that would meanlocksfor these individual levels should exist? If I acquired a lock on theObject, anotherThreadcannot call anymethodson thesame object, but if I acquired a lock on themethod, anotherthreadcan acquire lock on a differentmethod. Is this correct?
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?