问题
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 put
ting, it could have already been in the state before entering.
来源:https://stackoverflow.com/questions/5635923/linkedblockingqueue-thowing-interruptedexception