A design pattern that guarantees only one Runnable of a specific id value is executed by the pool

Suppose I have an ordered list of objects Runnableto be executed ExecutorService. My objects Runnablehave userIDfiled - let's say that I have about 20 different userID-s and 10 - the number of threads in the pool ( ExecutorServiceobject).

What is a common design pattern to ensure that no more than 1 Runnableobject of a particular group runs in one of the threads at a time? (The goal is that all Runnableof the same id group should be executed in chronological order and synchronously).

+4
source share
2 answers

You can create queues for each group, and when the task completes, you read the corresponding queue and, if necessary, send the next task.

- , Runnable . JDK , Guava, ExecutorService ListeningExecutorService. , ListenableFuture Java Future. ListenableFuture , . .

+1

SerialExecutor, JavaDocs of Executor. - Runnable. Opimized version https://github.com/rfqu/CodeSamples/blob/master/src/simpleactor/SerialExecutor.java, SerialExecutor Runnable , , .

0

Source: https://habr.com/ru/post/1527764/


All Articles