开发者

How can I call notify() in Java without blocking?

开发者 https://www.devze.com 2022-12-24 19:45 出处:网络
Are there a replacement for the follow Java code that will not block? I want only ping a possible waiting thread. I does not want change any on a possible thread that is already in the monitor.

Are there a replacement for the follow Java code that will not block? I want only ping a possible waiting thread. I does not want change any on a possible thread that is already in the monitor.

synchronized( monitor ) {
    开发者_如何学编程monitor.notify();
}


You could use java.util.concurrent.Semaphore instead of monitor. A binary semaphore can have the same use as a synchronize block:

private final Semaphore sema = new Semaphore(1, true); // binary: only 1 permit
....
try {
    sema.acquire();   // blocks till permit is available
    try {
        // critical section code
        ....
    } finally {
        sema.release();   // release permit
    }
} catch (InterruptedException ie) {
    ....

You can check the state of the semaphore with the following methods:

sema.availablePermits()  // 1 if no threads in critical section
sema.getQueueLength()    // number of threads blocked waiting on acquire
sema.getQueuedThreads()  // list of threads blocked waiting on acquire


The point of the notify is to let other threads that are waiting on the monitor know that they can try to obtain it. Only the current owner of the monitor can send the notify to indicate that they are done with it.

To own the monitor, you are obviously blocking any other thread. That is the purpose of the monitor after all.


Perhaps a ReentrantLock solve your problem? For example

class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }

Additionally, you can do stuff like

lock.isLocked()

and

lock.tryLock()


Try park/unpark with LockSupport.getBlocker()

http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/LockSupport.html


No you can not. You will get a "current thread not owner" if you try something like that.

0

精彩评论

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