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
thread
callsSharedResource.staticMethod
, it will acquire thelock
for theclass.
does it mean aninstance
ofSharedResource
, say x, will have to wait till it getslock
to exectutex.staticMethod
.Will
synchronization
ofthis
in ablock
, acquires the lock for that section of the code or for entireobject
. i.e can anotherthread
call the samemethod
on sameobject
; but execute the remainder of the code that is not part ofsynchronization block
If the above point is true, having a
dummy object
tolock
on does not provide any additional benefit. Correct?So there are different levels of
synchronziations
.Class
level,Object
level,method
level andblock level
. so that would meanlocks
for these individual levels should exist? If I acquired a lock on theObject
, anotherThread
cannot call anymethods
on thesame object
, but if I acquired a lock on themethod
, anotherthread
can 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?