My app receives messages from several users. Messages per user must be executed in order, but otherwise messages can be executed in parallel. How to implement such logic?
E.g. messages arrive in this order: u1:m1 u1:m2 u2:m1 u1:m3 u2:m2. Execution should be parallel like this:
- thread1:
u1:m1u1:m2u1:m3 - thread2:
u2:m1u2:m2
Number of users can be huge, therefore I can't just create a single threaded executor per user.
private ExcutorService executorService = newFixedThreadPool(10);
public void onMessage(String user, String message) {
// TODO schedule tasks per user in order
executorService.schedule(() -> processMessage(message));
}