public static interface ForkJoinPool.ManagedBlocker
ForkJoinPool
s接口。
一个ManagedBlocker
提供了两种方法。方法isReleasable
必须如果堵不必要报酬true
。方法block
阻止当前线程,如果有必要(也许内部调用isReleasable
其实之前阻塞)。这些行为被其他线程进行调用ForkJoinPool.managedBlock(ManagedBlocker)
。在这不寻常的方法适应同步API的可能,但不经常,长期阻滞。同样,他们允许更有效的内部处理的情况下,额外的工人可能是,但通常是没有,需要以确保足够的并行性。为此,isReleasable
方法的实现必须经得起重复调用。
例如,这里是一个managedblocker基于ReentrantLock:
class ManagedLocker implements ManagedBlocker {
final ReentrantLock lock;
boolean hasLock = false;
ManagedLocker(ReentrantLock lock) { this.lock = lock; }
public boolean block() {
if (!hasLock)
lock.lock();
return true;
}
public boolean isReleasable() {
return hasLock || (hasLock = lock.tryLock());
}
}
这里是一个类,可能在一个给定的队列中等待一个项目:
class QueueTaker<E> implements ManagedBlocker {
final BlockingQueue<E> queue;
volatile E item = null;
QueueTaker(BlockingQueue<E> q) { this.queue = q; }
public boolean block() throws InterruptedException {
if (item == null)
item = queue.take();
return true;
}
public boolean isReleasable() {
return item != null || (item = queue.poll()) != null;
}
public E getItem() { // call after pool.managedBlock completes
return item;
}
}
Modifier and Type | Method and Description |
---|---|
boolean |
block()
可能阻塞当前线程,例如等待锁或条件。
|
boolean |
isReleasable()
返回
true 如果阻塞是不必要的。
|
boolean block() throws InterruptedException
true
如果没有额外的封锁是必要的(即,如果isreleasable将返回true)
InterruptedException
如果中断等待(该方法不要求这样做,而是允许)
boolean isReleasable()
true
如果阻塞是不必要的。
true
如果阻塞是不必要的
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved.