ExecutorService that executes tasks sequentially but takes threads from a pool

后端 未结 6 1774
孤城傲影
孤城傲影 2021-02-20 11:22

I am trying to build an implementation of the ExecutorService, let\'s call it SequentialPooledExecutor, with the following properties.

6条回答
  •  被撕碎了的回忆
    2021-02-20 11:33

    private Map> sessionTasks = new HashMap<>();
    private ExecutorService pool = Executors.newFixedThreadPool(200);
    
    public void submit(int sessionId, Runnable task) {  
        if (sessionTasks.containsKey(sessionId)) {
            sessionTasks.compute(sessionId, (i, c) -> c.thenRunAsync(task, pool));
        } else {
            sessionTasks.put(sessionId, CompletableFuture.runAsync(task, pool));
        }
    }
    

    If a session has no task, a new task is created and run in the provided pool. If a session already has a tasks when a new task is added, the latter is chained (with thenRun) to the previous one, ensuring order.

提交回复
热议问题