java 中的事件循环

Event loop in java

我实际上正在尝试为 Nashorn (java 8) 编写一个事件循环,以便异步操作的回调(我启动的线程,例如,连接到远程服务或执行 long-运行ning 计算)将被放入队列并按顺序执行(不是并行)。我通过将回调函数放在 ConcurrentLinkedQueue 上并使用 ScheduledExecutorService 作为循环来检查要执行的回调队列。

工作正常,但我的问题是:

1) 在不拖动 CPU 的情况下,我可以使用多短的间隔?我将拥有多个 运行ning 并且它们必须相互独立。因此可能有 50 个线程都 运行 各自 "event loop"。例如,此执行程序每 10 毫秒尝试 运行 我的 运行 启用....

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(<cbRunnable>, 0, 10, TimeUnit.MILLISECONDS);

2) 这种方法是否优于:

while (true) {
   // check queue and execute any callback...
}

3)有没有更好的方法?

答案完全取决于您在此块中所做的事情:

while (true) {
    // check queue and execute any callback...
}

如果队列检查阻塞直到元素可用,那么就 CPU 用法而言,这是 "most efficient" 轮询方式。如果检查没有阻塞,那么调用线程将自旋,并且在循环期间你将成为 运行 一个满负荷的硬件线程 - 然而,这消除了同步成本并且会给你绝对最好的 响应时间。以下是一些示例:

阻塞队列(对 CPU 的负担最少,但以同步为代价)

Queue<T> q = new LinkedBlockingQueue<>();
...
while(true){
    T t = q.take();
    //t will never be null, do something with it here.
}

Non-blocking 队列(在 CPU 上最费力,但没有同步成本)

Queue<T> q = new LinkedList<>();
...
while(true){
    T t;
    while((t = q.poll()) == null); //busy polling!
    //t will never be null, do something with it here
}

ScheduledExecutorService

最后...如果您最终使用预定的执行程序服务,您将在轮询之间强制等待一些 non-zero 时间。与 full-on BlockingQueue 实施相比,这几乎与 CPU-wise 一样高效,但您也被迫在响应时间上受到影响,直到调度间隔。 "best" 对你的应用程序来说是什么取决于你是否有能力等待轮询之间的最短睡眠时间(我认为你可以安排微秒......?),或者你是否需要更快的东西,比如繁忙的轮询方案。