Java: ExecutorService that blocks on submission after a certain queue size

前端 未结 7 1382
Happy的楠姐
Happy的楠姐 2020-11-30 17:38

I am trying to code a solution in which a single thread produces I/O-intensive tasks that can be performed in parallel. Each task have significant in-memory data. So I want

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 18:01

    I have done this same thing. The trick is to create a BlockingQueue where the offer() method is really a put(). (you can use whatever base BlockingQueue impl you want).

    public class LimitedQueue extends LinkedBlockingQueue 
    {
        public LimitedQueue(int maxSize)
        {
            super(maxSize);
        }
    
        @Override
        public boolean offer(E e)
        {
            // turn offer() and add() into a blocking calls (unless interrupted)
            try {
                put(e);
                return true;
            } catch(InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
            return false;
        }
    
    }
    

    Note that this only works for thread pool where corePoolSize==maxPoolSize so be careful there (see comments).

提交回复
热议问题