“Closing” a blocking queue

前端 未结 10 701
不思量自难忘°
不思量自难忘° 2021-01-30 09:13

I’m using java.util.concurrent.BlockingQueue in a very simple producer-consumer scenario. E.g. this pseudo code depicts the consumer part:

class QueueCo         


        
10条回答
  •  佛祖请我去吃肉
    2021-01-30 10:05

    An alternative would be to wrap the processing you're doing with an ExecutorService, and let the ExecutorService itself control whether or not jobs get added to the queue.

    Basically, you take advantage of ExecutorService.shutdown(), which when called disallows any more tasks from being processed by the executor.

    I'm not sure how you're currently submitting tasks to the QueueConsumer in your example. I've made the assumption that you have some sort of submit() method, and used a similar method in the example.

    import java.util.concurrent.*;
    
    class QueueConsumer {
        private final ExecutorService executor = Executors.newSingleThreadExecutor();
    
        public void shutdown() {
            executor.shutdown(); // gracefully shuts down the executor
        }
    
        // 'Result' is a class you'll have to write yourself, if you want.
        // If you don't need to provide a result, you can just Runnable
        // instead of Callable.
        public Future submit(final ComplexObject complexObject) {
            if(executor.isShutdown()) {
                // handle submitted tasks after the executor has been told to shutdown
            }
    
            return executor.submit(new Callable() {
                @Override
                public Result call() {
                    return process(complexObject);
                }
            });
        }
    
        private Result process(final ComplexObject complexObject) {
            // Do something with the complex object.
        }
    }
    

    This example is just an off-the-cuff illustration of what the java.util.concurrent package offers; there are probably some optimizations that could be made to it (e.g., QueueConsumer as its own class probably isn't even necessary; you could just provide the ExecutorService to whatever producers are submitting the tasks).

    Dig through the java.util.concurrent package (starting at some of the links above). You might find that it gives you a lot of great options for what you're trying to do, and you don't even have to worry about regulating the work queue.

提交回复
热议问题