0

I want a ThreadPool to execute customer orders, multiple orders should be processed parallel, but for the same customer orders should be processed in a generated sequence. Which means if any thread already processing customerA order then no other thread can process CustomerA's next order until first order is processed.

Are there any ThreadPool implementations which serve my case ?

ravthiru
  • 8,878
  • 2
  • 43
  • 52
  • The built-in ones don't have that out of the box, but you could easily customize them to support that. – Kayaman Nov 04 '15 at 10:11

2 Answers2

1

I do not think that there are such standard functionality of ThreadPools. What you need to do is to create 'dispatcher' that will 'assign threads' from pool to customer orders. It should save an internal map of unique order id -> thread. If there is an order in processing new updates for this order should wait.

For this task you should look into actor model (and akka - as it's implementation). It allows easily describe this solution.

vvg
  • 6,325
  • 19
  • 36
0

Simple implementation:

public class CustomerOrderedExecutor {
    private final Map<Integer, Executor> executors;
    private final int poolSize;

    public CustomerOrderedExecutor(int poolSize) {
        this.poolSize = poolSize;
        ImmutableMap.Builder<Integer, Executor> builder = ImmutableMap.builder();
        for (int i = 0; i < poolSize; i++) {
            builder.put(i, Executors.newSingleThreadExecutor());
        }
        executors = builder.build();
    }

    void execute(Runnable command, int customerId) {
        executors.get(customerId % poolSize).execute(command);
    }
}
Anatoly Deyneka
  • 1,238
  • 8
  • 13