开发者

Checking programmatically whether lock is granted?

Like in wait() method if lock is not granted on calling object(for wait()) like by sychronizing on on calling object ,it throws IllegalMonitorStateExcept开发者_JAVA百科ion.

I want to know that

Like wait() method, can we make sure lock is granted ,by writing some code?? or is it done by JVM only ??


Just write:

synchronized (thing) {
    thing.wait ();
}

If it's not already locked, it will be locked, and if it already locked, then it's fine.


You can call Thread.holdsLock() to find out if a lock is held. However you should design your code so that you know whether you have a lock or not. You should be able to determine this staticly.

notify/wait was useful pre-Java 5. If you have Java 5 or later, using the concurrency library is likely to be a better choice.

EDIT: I was referring to the concurrent package http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html added in 2004, http://download.oracle.com/javase/tutorial/essential/concurrency/highlevel.html before then it was an external concurrency library. http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html


I don’t know Java, but the usual lock semantics is that when you try to acquire a lock, you block until you get it. This means that there is no need to verify that you actually got the lock – when the flow gets to the next line, you can be sure you are locked. When you start trying to do other things with the locks, like trying to check if it’s locked or not, you are usually doing it wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜