Catching InterruptedException Error
Please check the code snippet below:
public class Task implements Runnable { private final BlockingQueue queue = ...; @Override public void run() { while (!Thread.currentThread().isInterrupted()) { String result = getOrDefault(() -> queue.poll(1L, TimeUnit.MINUTES), "default"); //do smth with the result } } T getOrDefault(Callable supplier, T defaultValue) { try { return supplier.call(); } catch (Exception e) { logger.error("Got exception while retrieving value.", e); return defaultValue; } } }
The problem with the code is that while waiting for a new element in the queue, it is It is impossible to terminate the thread because the interrupted flag is never restored:
1. The thread running the code is interrupted.
2.BlockingQueue # The poll() method throws InterruptedException and clears the interrupt flag.
3.The judgment of the loop condition (!Thread.currentThread().isInterrupted()) in while is true because the mark has been cleared.
To prevent this behavior, always catch when a method is thrown explicitly (by declaring it to throw an InterruptedException) or implicitly (by declaring/throwing a primitive exception) InterruptedException exception and restore the interrupted flag.
T getOrDefault(Callable supplier, T defaultValue) { try { return supplier.call(); } catch (InterruptedException e) { logger.error("Got interrupted while retrieving value.", e); Thread.currentThread().interrupt(); return defaultValue; } catch (Exception e) { logger.error("Got exception while retrieving value.", e); return defaultValue; } }
The above is the detailed content of How to catch InterruptedException error in java. For more information, please follow other related articles on the PHP Chinese website!