• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads  RSS feed

 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way to find out out whether an object is locked by any threads.Say i want to enter into a synchronized code(synchronized on an object (say A).Now A will be locked.So my new thread will wait for the locks of A to be released.But i dont want this to happen.I just want my new thread to do something else when the object A is locked and not wait for the locks to be released.Is this possible,without using a private flag to indicate the lock condition???
 
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From API:

holdsLock
public static boolean holdsLock(Object obj)Returns true if and only if the current thread holds the monitor lock on the specified object.
This method is designed to allow a program to assert that the current thread already holds a specified lock:
assert Thread.holdsLock(obj);

Parameters:
obj - the object on which to test lock ownership
Returns:
true if the current thread holds the monitor lock on the specified object.
Throws:
NullPointerException - if obj is null
Since:
1.4
 
Ashok C. Mohan
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But i dont want to check whether the current thread holds lock on an object.I want to check whether any other thread has the lock on an object.How can i do that?
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ashok C.M.:
But i dont want to check whether the current thread holds lock on an object.I want to check whether any other thread has the lock on an object.How can i do that?

I don't know that there is an easy way to do that. My guess is that, if you wanted to pull this off, you'd have to "invent" your own solution by using a variable that you set at the beginning of a synchronized block and unset at the end.
Regardless, this concept is certainly not on the SCJP exam so I'm moving this to Java in General (Intermediate).
Corey
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!