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

holdsLock is working strange

 
Mihai Radulescu
Ranch Hand
Posts: 918
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hallo I prepare my self for the developer exam and during this process I stuck my self in somthig that my be vrey easy.On short I have the code :



If I run ti I have the output :

Curent thread : Thread 1
Thread 1 has monitor : true
Thread 2 has monitor : true
Thread-3 has monitor : true
Curent thread : Thread 2
Thread 1 has monitor : true
Thread 2 has monitor : true
Thread-3 has monitor : true

Ok lets analyze it:
1.The method is synchronized so only one thread can enter one,(and owns the monitor).
2.If only one thread can enter in method testSyncron() once, why both threads retuns true on holdsLock(this), one thread must leave the method(and lose its monitor) to let the other one to gain access to the monitor.In this way at least one must return flase on holdsLock(this).
3.Thread t3 (Thread-3) even is not running -it is just created(no start method was call on it) ,how that it holds the monitor ?


Why this strange output ?

[Andrew: Put code between [code] and [/code] UBB tags]
[ November 16, 2004: Message edited by: Andrew Monkhouse ]
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 12014
220
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mihai,

Please put your code between [code] and [/code] UBB tags, as this ensures that your indenting is preserved, which makes the code easier to read and makes it easier for people to read (which increases your chances of getting a response).

The Thread.holdsLock() method is a static method which implictly works on the current thread only. It is designed for the cases where you wish to verify (or assert) that you do own the lock. It cannot be used to verify whether another thread owns a lock.

Regards, Andrew
 
Mihai Radulescu
Ranch Hand
Posts: 918
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Andrew, now all make sense.I just look in the java api and I find something similar : "(holdsLock) Returns true if and only if the current thread holds the monitor lock on the specified object".
I 'll try in the future to use the UBB codes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic