Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Nested Synchronization

 
Chris Bicnal
Ranch Hand
Posts: 99
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

I've got a question regarding synchronized blocks. Let's consider the following class...

... so basically I've got a thread that already owns the lock on lockObj1 calling another method that tries to get the lock on lockObj1 again.

Am I correct in thinking that because first thread (let's call it thread1) owns the lock of lockObj1 from method1 it wont be held up when it comes across the synchronized(lockObj1) line in method2 because it already owns this lock?

Does anyone see any problems with this approach?

Thanks in advance,

Chris

[Edit: Put code inside UBB code tags to try to make it more readable. - Andrew]
[ September 14, 2008: Message edited by: Andrew Monkhouse ]
 
John Donoghue
Ranch Hand
Posts: 45
IntelliJ IDE Mac OS X Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In terms of a thread blocking itself, the answer is no. Java threads are reentrant. The same thread can enter multiple synchronized sections in the same object and will not block iteslf.
One issue to worry about is that the design is locking on separate objects. This raises the question of deadlock; it is possible to that one thread gets the lock on object1, and then the thread scheduler swaps it out for another thread. That thread gets lock on object2, and then blocks waiting for object1. The first thread starts to run again, and blocks waiting for object2--deadlock. I'd think carefully about this, and make really sure to document it for the examiner.

You could synchronize the blocks on *this*, if you don't want to synchronize the entire method. If the two methods are in the same class, why not just synchronize the methods instead? This seems like a much simpler solution to verify.
 
Jeffry Kristianto Yanuar
Ranch Hand
Posts: 759
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm, be careful about deadlock. In my assignment I only have 1 lock to be synchronized before accessing a particular object. If you feel that you must do so, be careful about deadlock and document your decision.

Good luck !!

Jeffry Kristianto Yanuar
Java Instructor
SCJP 5.0
SCJA
SCJD (Working on UrlyBird 1.3.2) --> preparing to upload
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic