hi i really dont uderstand the difference between synchronized blocks & synchronized methods. As far as i have studied it,I think by synchronized block we can obtain lock in the object mentioned in synchronized(Obj ref) Does this mean that other methods (which are not synchronized)of the same object wont be accessible to any other thread until current thread releases the monitor? please help me out in knowing the exac use of synchronized blocks.
Synchronized methods are always synchronized on the object in which they are defined. Non-static methods synchronize on the instance. So, these two methods work in the same way:
Static methods synchronize on the class itself. Therefore, these two are the same:
The advantage of using the synchronized block is that you can synchronize on objects other than the method's class / instance. For example, you can use it to synchronize on the inner data member. Also, you can limit the scope of synchronization, which is a good way to increase performance in a multithreaded environment. Synchronized methods, on the other hand, are simpler, their behavior can be guessed just by looking at the API. However, sometimes it is not enough to just synchronize methods to achieve thread safety. The Vector class is a good example for this. [ November 13, 2006: Message edited by: David Nemeskey ]
Joined: Apr 29, 2006
so that means by synchronized blocks we can have a lock on a particular object.eg. if we have a Object ob=new Object() then we can even use this object to have a lock on some part of method
Also David in the link that you had mentioned ,it was given as..calling another method from a synchronized block can give unwanted result... i really dont understand what does this mean...can you explain if possible with some example. Thaks a lot David for your help
Joined: Nov 08, 2006
Yes, you can certainly do that. But please note that the synchronized block can be in any part of the method, it is not required to enclose the entire method code. So, this
is perfectly valid as well...
Also, it is always a better idea to synchronize on the object to which you want to control access, not just a random one. For example the inner data member, etc.
As for calling other methods from synchronized methods and blocks: as far as I know the only "unwanted" result is that each instruction (including those in the invoked methods) will also be part of the same synchronization block. To understand this, you have to remember, that synchronization affects the thread running the code, not "the code itself". Since invoked methods also run by the same thread, they will also be synchronized. In my opinion, this is not "unwanted", but just how it should work.
One thing to be aware of is when there is another synchronized block in a called method, and it is synchronized on a different object than the first block. You have to be careful not to run into a deadlock like this...