被异步通知具有项目可用的BlockingQueue [英] Being asynchronously notified of a BlockingQueue having an item available

查看:66
本文介绍了被异步通知具有项目可用的BlockingQueue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当某些 BlockingQueue 有物品要送给我时,我需要一个 Object 来异步通知。

I need an Object to be asynchronously notified when some BlockingQueue has got an item to give.

我已经在Javadoc和网络上搜索了预制的解决方案,然后最终得到了我的(也许很幼稚)的解决方案,这里是:

I've searched both Javadoc and the web for a pre-made solution, then I ended up with a (maybe naive) solution of mine, here it is:

interface QueueWaiterListener<T> {
    public void itemAvailable(T item, Object cookie);
}

class QueueWaiter<T> extends Thread {

    protected final BlockingQueue<T> queue;
    protected final QueueWaiterListener<T> listener;
    protected final Object cookie;

    public QueueWaiter(BlockingQueue<T> queue, QueueWaiterListener<T> listener, Object cookie) {
        this.queue = queue;
        this.listener = listener;
        this.cookie = cookie;
    }

    public QueueWaiter(BlockingQueue<T> queue, QueueWaiterListener<T> listener) {
        this.queue = queue;
        this.listener = listener;
        this.cookie = null;
    }

    @Override
    public void run() {
        while (!isInterrupted()) {
            try {
                T item = queue.take();
                listener.itemAvailable(item, cookie);
            } catch (InterruptedException e) {
            }
        }
    }
}

基本上,队列的 take()操作上有一个线程阻塞,每次 take()操作成功,可以选择发送回一个特殊的 cookie 对象(如果需要,可以忽略它)。

Basically, there's a thread blocking on a take() operation of a queue that callbacks a listener object everytime a take() operation succeeds, optionally sending back a special cookie object (ignore it if you want).

问题是:还有更好的方法吗?我是否在做一些不可原谅的错误(在并发性/效率和/或代码清洁性方面)?

Question is: is there any better way to do this? Am I doing some unforgivable mistake (both in concurrency/efficiency and/or code cleanness)? Thanks in advance.

推荐答案

也许您可以将某些 BlockingQueue 子类化(例如作为 ArrayBlockingQueue LinkedBlockingQueue 或您正在使用的内容),添加对侦听器的支持并执行

Perhaps you could subclass some BlockingQueue (such as ArrayBlockingQueue or LinkedBlockingQueue or what ever you're using), add support for listeners and do

@Override
public boolean add(E o) {
    super.add(o);
    notifyListeners(o);
}

这篇关于被异步通知具有项目可用的BlockingQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆