Thread pool that binds tasks for a given ID to the same thread

前端 未结 6 1904
别那么骄傲
别那么骄傲 2020-12-28 17:19

Are there any implementations of a thread pool (in Java) that ensures all tasks for the same logical ID are executed on the same thread?

The logic I\'m after is if t

6条回答
  •  我在风中等你
    2020-12-28 17:56

    I have to implement a similar solution and the suggestion of creating an array of executor services by h22 seems the best approach to me with one caveat that I will be taking the modulus % of the ID (either the raw ID assuming it is long/int or the hash code) relative to some desired max size and using that result as the new ID so that way I can have a balance between ending up with way too many executor service objects while still getting a good amount of concurrency in the processing.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class ExecutorServiceRouter {
    
        private List services;
        private int size;
    
        public ExecutorServiceRouter(int size) {
            services = new ArrayList(size);
            this.size = size;
            for (int i = 0; i < size; i++) {
                services.add(Executors.newSingleThreadExecutor());
            }
        }
    
        public void route(long id, Runnable r) {
            services.get((int) (id % size)).execute(r);
        }
    
        public void shutdown() {
            for (ExecutorService service : services) {
                service.shutdown();
            }
        }
    
    }
    

提交回复
热议问题