Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent request processing in Java with constraints

Suppose I need to process requests of 3 types: A, B, and C as follows:

  • Requests are processed concurrently.
  • There are at most K (<= 3) requests to be processed concurrently at the same time.
  • Requests of the same type cannot be processed at the same time.

More generally, the number of types is N and the number of concurrent requests is K <= N.

How would you implement it in Java with java.util.concurrent?

like image 779
Michael Avatar asked Oct 11 '13 07:10

Michael


1 Answers

You can not process K requests at the same time, that will break second rule. Maximum number of concurrent requests is number types. In your case its three. So make three queues and attache them to three threads. Thats the only way. Executors.newSingleThreadExecutor implements this technique.

public static void main(String[] args) {
    int N = 2;
    int K = 3;
    List<Executor> executors = new ArrayList<Executor>(N);
    for(int i = 0; i < N; i++){
        executors.add(Executors.newSingleThreadExecutor());
    }
    Map<Type, Executor> typeExecutors = new HashMap<Type, Executor>(K);
    int i = 0;
    for(Type t : Type.values()){
        typeExecutors.put(t, executors.get(i++ % executors.size()));
    }
}

enum Type{
    T1, T2, T3
}
like image 90
Mikhail Avatar answered Oct 12 '22 11:10

Mikhail