Behaviour of multiple Synchronized blocks in the same class
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   pradeep_kanwar
Posted On:   Friday, March 14, 2003 02:54 AM

Hi, I have two threads which are passed the same object ( reference not value). The object belongs to a class which has two methods methodA() and methodB() both of them 'synchronized' methods. What happens when the first thread operates on methodA and thread 2 operates on methodB() of the object simultaneously.Since the object is the same and the first thread has a lock over a methodA will the second thread be able to work on the methodB simultaneously ? Now the tricky bit.. assume there is another methodC() which is also synchronized. What will happen if both the methods , methodA() and methodB() finally make calls to the methodC(). Will the threads ask for new locks or will they reuse their current locks ( re-entrancy in java will give the same lock i thi   More>>

Hi,
I have two threads which are passed the same object ( reference not value). The object belongs to a class which has two methods methodA() and methodB() both of them 'synchronized' methods. What happens when the first thread operates on methodA and thread 2 operates on methodB() of the object simultaneously.Since the object is the same and the first thread has a lock over a methodA will the second thread be able to work on the methodB simultaneously ? Now the tricky bit.. assume there is another methodC() which is also synchronized. What will happen if both the methods , methodA() and methodB() finally make calls to the methodC(). Will the threads ask for new locks or will they reuse their current locks ( re-entrancy in java will give the same lock i think ). So will it be right if i said that the locks are unique key attached to an object/thread combination. It does not matter what synchronized part of the object/class the thread is dealing with. The thread will use the same lock till its done with the processing with that object/class. Am i right ?

   <<Less

Re: Behaviour of multiple Synchronized blocks in the same class

Posted By:   pradeep_kanwar  
Posted On:   Friday, March 14, 2003 06:19 PM



I did some testing on my own and here is what i found out.

  1. if methodA and methodB are both synchronized and are accessed by two diff threads then it will allow them to operate on the same object simulataneously
  2. The locks on methods are implicit and equal to a lock on 'this'
  3. A thread will use the same lock for the block of synchronized code. If you are making a call to another block of synchronized code which gives you another explicit lock then you have two locks. the one from the original method ( implicit) and this one (explicit).



I guess i have answered myself. Please post any comment if you think my interpretation is wrong. rgds, pradeep
About | Sitemap | Contact