“Closing” a blocking queue

前端 未结 10 845
不思量自难忘°
不思量自难忘° 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条回答
  •  Happy的楠姐
    2021-01-30 09:41

    Another possibility for making a poison object: Make it be a particular instance of the class. This way, you do not have to muck around subtypes or screw up your generic.

    Drawback: This won't work if there's some sort of serialization barrier between the producer and consumer.

    public class ComplexObject
    {
        public static final POISON_INSTANCE = new ComplexObject();
    
        public ComplexObject(whatever arguments) {
        }
    
        // Empty constructor for creating poison instance.
        private ComplexObject() {
        }
    }
    
    class QueueConsumer implements Runnable {
        @Override
        public void run() {
            while(!(Thread.currentThread().interrupted())) {
                try {
                    final ComplexObject complexObject = myBlockingQueue.take();
                    if (complexObject == ComplexObject.POISON_INSTANCE)
                        return;
    
                    // Process complex object.
    
                } catch (InterruptedException e) {
                    // Set interrupted flag.
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
    

提交回复
热议问题