Can anyone be kind enough to explain this synchronization:
The above synchronized block is taking "msg" as a monitor and not the object that the display method will be called on. Can you explain what might be some cases where this can be useful and is it the same as doing synchronized(this).
Prompt help is greatly appreciated.
Vibhor Chandel wrote:Hi Mike,
That's what I need to know, if its not good then why is it not good. Is the synchronized block no synchronized this way. Just want some knowledge about the monitor objects and the role they play in making a block synchronized.
As far as the Java language and the mutual exclusion behavior of the code is concerned, it doesn't matter what object you sync on. All that matters in that respect is that all threads accessing a particular shared resource sync on the same lock.
Now, having said that, some objects may be more or less appropriate as locks in some situations. The two most common are:
1) Sync on the mutable object that's being modified. For instance, this is what Collections.syncrhonizedXxx() does. All the methods on the returned collection are synced on that collection, and when you iterate over that collection, you must also sync on that collection around your iteration loop. This way, all uses of that mutable object are synced on the same lock--that object's lock.
2) Sync on an Object created just for the purpose of being a mutex lock. This is useful when you want to ensure exclusive access within your class, but you don't want to use an object that anybody else can also possibly grab as a lock. You make a private final Object lock = new Object(); field and sync on that.
There really should be no reason to ever sync on a String. And doing so can have negative repercussions. For instance, if the String happens to be one that's in the constant pool, then it's too easy for many unrelated groups of threads to be syncing on the same String.
Vibhor Chandel wrote:So in the code i have above I get a lock on the String msg and get the code inside the block synchronized. Isn't this the same thing if we have synchronized the display method instead. I mean both will restrict access to the block right?
Only if other calls to display are syncing on the same String. If T1 calls display("x"); and T2 calls display("y"); then both can execute at the same time. Remember, syncing only prevents access to a block or method when all the threads in question sync on the same lock.
If you declare the display method as synced, then its as if its body was synced on this, so every thread calling display on that particular object will have to go in one at a time.