0

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?
    }

}
James Raitsev
  • 92,517
  • 154
  • 335
  • 470
dieter
  • 2,551
  • 3
  • 17
  • 6
  • Do you always get an interrupt exception every time you call shutdown. Where do you call shutdown from? Also a little confusing that you have a two variables named messages. – richs Apr 12 '11 at 13:57
  • On startup it can happen that a shutdown has to be done because of a wrong version. The app starts alot of threads and at the same time has to shut them down again. So it could be that shutdown is called while the Thread is starting. But this shouldn't be a problem? – dieter Apr 12 '11 at 14:30
  • Does calling shutdown always cause an InterruptedException? Can you print the stack trace? – richs Apr 12 '11 at 14:35

1 Answers1

2

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.

John Vint
  • 39,695
  • 7
  • 78
  • 108
  • Does that happen when the Thread is started? So it is better to use add instead? – dieter Apr 12 '11 at 13:30
  • 1
    The thread when started should never be interrupted. You can use add, but if the queue is full the MessageFactory.getPoison() will never be added in to the queue (assuming the implementation changes to ArrayBlockingQueue or you add a size restriction). You should try to find out where or why the thread is being interrupted. If youre using an executor for example, Future.cancel(true) will interrupt the thread. – John Vint Apr 12 '11 at 13:47