Can anyone please tell me what it means by saying,
"When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired. But when you synchronize a block of code, you specify which object's lock you want to use as the lock.
Guys I'm faling to understand what it means. Can anyone please tell me this with an example for synchronized block code trying to be accessed by multiple threads??
Dear John, Though what you have stated is extermely true but it seems that your answer is not very specialized towards the question raised by jothi.
When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired
what I think is for executing a syncronized method of an object you need to aquire the lock for the same object in which the method is defined(same line restated).Lets have an example
To execute the method mymethod() by a thread the thread must aquire a lock on the MyLockEx instance.So every time it is the same object in which the syncronized method is defined should be used as a lock to invoke the syncronized method defined within it. This above code is similar to a syncronized block having this as a argument like
Doing so will make the method more flexible as you are free syncronize the statements of your choice not all the method ,as John stated in this answer.
But when you synchronize a block of code, you specify which object's lock you want to use as the lock.
While using the syncronized block you can use the object of your choice as a lock. .Two benefits of syncronized blocks .Isntit?
Hi , I am agree with Sanjeev Singh he has poured his knowledge on your problem. I am going to explain basic of Synchronization. Synchronization means set threads in a sequence that no more than one thread can access a single resource at a moment.So java people launched this concept.There is no locking ability in java.it is only mechanism .Through java(JVM) you can only tell to operating system that we want lock on this object.So come on main topic
Synchronised a method and Synchronised a block are same having no difference. Same concept will be apply on method synchronisation as well as on block .Actually loading time every information regarding class load in memory.So method is member of class having some name .So it is already set by Java people that if Synchronised a method means lock must be accuired by that accessor object.but you think if need is to safe only 4 lines out of 50 lines of that method. then will you Synchronized whole method? So at this situation java people gave another concept means Synchronized block of code which is thread-unsafe. By doing this you will get performance inhancement. i think there is no need to explame it through example because Mr. Sanjeev Singh has explained it very well.
Thanks to John for asking it. thanking to Sanjeev for nice explanation . [ November 04, 2006: Message edited by: Prashant kumar Singh ]