ExecutorService:按键先进先出排序

ExecutorService: FIFO ordering by key

我正在寻找使 ExecutorService 成为按对象(键)排序的 FIFO 的方法,即

  1. 对于给定的键,事件将按照它们到达的顺序进行处理。
  2. 对于给定的键,一次只会处理一个事件。

Netty 3 有 OrderedMemoryAwareThreadPoolExecutor 但它与 Netty 绑定。

Guava 有 EventBus 但不清楚是否保证 FIFO。

我可以使用 JKeyLockManager 之类的方法锁定密钥,但为了保证 FIFO,我将不得不冒在调度程序线程中争用的风险。

是否有解决此问题的通用解决方案?

如果你想要简单,我会像这样使用多个 FIFO 执行器

static final int executors = Runtime.getRuntime().availableProcessors() * 2;
ExecutorService[] executors = new ExecutorService[executors];
// fill with single threaded executors.

public Future submit(Object actorId, Runnable r) {
    int h = (actorId.hashCode() & 0x7FFF_FFFF) % executors;
    return executors[h].submit(r);
}

除非工作负载高度不平衡,否则这将使您的所有 CPU 都处于忙碌状态,而无需锁定。