Is this interrupt required ()?

Here's a 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(); } } } } 

Like the above code, even if we put the LoggerThread.interrupt () method in the stop () method, the interrupt is simply captured by the thread and does nothing.

So you need LoggerThread.interrupt () ?

+5
source share
1 answer

Yes, it is necessary. If the queue is empty, this String msg = queue.take(); statement String msg = queue.take(); will be blocked until the item is queued or interrupted.

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

However, it seems to crash: if reservations not 0 when you call the close method and the queue is empty, it seems that your loop will continue to work and hang on queue.take() in the while loop iterate after interruption.

+6
source

Source: https://habr.com/ru/post/1234246/


All Articles