我希望有一个回调机制,当达到队列大小限制时,我会在其中收到通知…
我不会将执行器子类化,但会将执行
BlockingQueue器使用的子类化。像下面这样的东西应该起作用。
checkUnsaturated()如果删除条目并将某人放回原处,则代码中存在竞争条件。如果这些条件需要完善,则可能必须在队列上进行同步。另外,我也不知道执行器实现使用什么方法,因此您可能不需要覆盖其中的一些方法。
public class ObservableBlockingQueue<E> extends linkedBlockingQueue<E> { private ISaturatedPoolObserver observer; private int capacity; public ObservableBlockingQueue(ISaturatedPoolObserver observer, int capacity) { super(capacity); this.observer = observer; this.capacity = capacity; } @Override public boolean offer(E o) { boolean offered = super.offer(o); if (!offered) { observer.onSaturated(); } return offered; } @Override public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException { boolean offered = super.offer(o, timeout, unit); if (!offered) { observer.onSaturated(); } return offered; } @Override public E poll() { E e = super.poll(); if (e != null) { checkUnsaturated(); } return e; } @Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { E e = super.poll(timeout, unit); if (e != null) { checkUnsaturated(); } return e; } @Override public E take() throws InterruptedException { E e = super.take(); checkUnsaturated(); return e; } @Override public boolean remove(E e) throws InterruptedException { boolean removed = super.remove(e); if (removed) { checkUnsaturated(); } return removed; } private void checkUnsaturated() { if (super.size() * 100 / capacity < UNSATURATED_PERCENTAGE) { observer.onUnsaturated(); } }}


