Home > Java > javaTutorial > body text

How to catch InterruptedException error in java

WBOY
Release: 2023-04-18 20:10:34
forward
879 people have browsed it

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;
		}
	}
}
Copy after login

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;
	}
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template