Suppose I need to process requests of 3 types: A, B, and C as follows:
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
?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With