LinkedBlockingQueue thowing InterruptedException

旧巷老猫 提交于 2019-12-20 07:22:32

问题


I have this piece of code. A LinkedBlockingQueue should only throw an Exception if interrupted while waiting to add to the queue. But this queue is unbounded so it should add asap. Why does my shutdown methode throw an InterruptedException?

private final LinkedBlockingQueue<Message> messages= new LinkedBlockingQueue<Message>();

public void run(){
    LinkedList<Message> messages = new LinkedList<Message>(); 
    while (true){
        try{
            messages.clear();
            messages.add(this.messages.take());
                            this.messages.drainTo(messages);
            for (Message message:messages){
                if(message.isPoison())return;
                doSomething(message);
            }
        }catch(Exception e){
            getLogger().addException(e);
        }
    }
}


protected void add(Message m){
    try {
        messages.put(m);
    }catch (InterruptedException e) {
        getLogger().addException(e);
        addRollback(e);
    }
}

public void shutdown(){
    try{
        messages.put(MessageFactory.getPoison());
    }catch(InterruptedException e){
     //here an exception is thrown. Why?
    }

}

回答1:


If the thread is in a state of interruption, that is Thread.interrupted() == true, then the call will throw an InterruptionException. It doesn't necessarily mean that the thread was interrupted while you were putting, it could have already been in the state before entering.



来源:https://stackoverflow.com/questions/5635923/linkedblockingqueue-thowing-interruptedexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!