user2916610
user2916610

Reputation: 765

Is this interrupt() necessary?

Here's the snippet:

public class LogService {

    public void stop() {
        synchronized (this) { isShutdown = true; }
        loggerThread.interrupt();    /* Is it necesarry? */
    }

    public void log(String msg) throws InterruptedException {
        synchronized (this) {
            if (isShutdown)
            throw new IllegalStateException(...);
            ++reservations;
        }
        queue.put(msg);
    }

    private class LoggerThread extends Thread {
        public void run() {
            try {
                while (true) {
                    try {
                        synchronized (LogService.this) {
                            if (isShutdown && reservations == 0)
                                break;
                        }
                        String msg = queue.take();
                        synchronized (LogService.this) {
                        --reservations;
                        }
                        writer.println(msg);
                    } catch (InterruptedException e) { }    /* Do nothing */
                }
            } finally {
                writer.close();
            }
        }
    }
}

As the code above, Even if we put LoggerThread.interrupt() in stop() method, the interruption just be caught by thread and do nothing.

So is LoggerThread.interrupt() necessary?

Upvotes: 5

Views: 128

Answers (1)

assylias
assylias

Reputation: 328568

Yes it it necessary. If the queue is empty, this statement String msg = queue.take(); will block until an element is put in the queue or it is is interrupted.

If you want to guarantee that the thread does not hang you need to interrupt it.

However there seems to be a glitch: if reservations is not 0 when you call the close method AND the queue is empty, it seems that your loop will keep going and hang on queue.take() at the while loop iteration following the interruption.

Upvotes: 6

Related Questions