• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding synchronized blocks

 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I am studying synchronization and thread interaction. Please have a look at the following class:



In the main() thread , we are instantiating the Calculator class. Next we are passing that calculator reference to create 3 distinct objects of Reader class and calling start() method on these objects. My question is that how come is it possible that all 3 different Reader objects are locking on the same calculator instance. Obviously when we pass a reference variable , we pass copy of bits that refer to the same Calculator object on the heap right. How come that 3 Reader threads are locking on same calculator object? The rule says that if one thread has acquired a lock on an object, no other thread can acquire that lock unless that thread releases the lock. Correct?
 
Florin Vasile
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that the wait method releases the locks. so each thread will acquire the lock on the calculator object and release it on wait. After you execute notifyall each one will obtain the lock (each at a time) and continue to completion.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Florin Vasile, welcome to the Ranch
Try the Java Tutorials.
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Florin Vasile wrote:I believe that the wait method releases the locks. so each thread will acquire the lock on the calculator object and release it on wait. After you execute notifyall each one will obtain the lock (each at a time) and continue to completion.


I need to ask you another thing Florin. How do I know that the calculation has not completed before the 3 Reader threads call wait and release locks on the calculator instance. What stops the JVM from running the calculator.start() thread first? Then all the three threads could be left waiting for something that has actually already been completed. Right?
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Florin Vasile, welcome to the Ranch
Try the Java Tutorials.


There are a lot of topics in the Java link you provided. Could you be more specific as to which one of them should I study to seek an answer to my question Ritchie?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic