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?
Interrupts are commonly used by hardware devices to indicate electronic or physical state changes that require time-sensitive attention. Interrupts are also commonly used to implement computer multitasking, especially in real-time computing. Systems that use interrupts in these ways are said to be interrupt-driven.
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
interrupt() occurs while that thread is executing. The . interrupt() method sets the "interrupted" flag for that thread and interrupts any IO or sleep operations. It does nothing else, so it's up to your program to respond appropriately- and check its interrupt flag, via Thread.
InterruptedExceptions should never be ignored in the code, and simply logging the exception counts in this case as "ignoring". The throwing of the InterruptedException clears the interrupted state of the Thread, so if the exception is not handled properly the information that the thread was interrupted will be lost.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With