Get the App
SLTechnology News&Howtos  ›  Development  › 

How java catches InterruptedException errors

Shulou Source: shulou.com Published: 2022-06-01 04:51:06 09月22日 Update

Editor to share with you how java catches InterruptedException errors, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Catch InterruptedException error

Check the following code snippet:

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 it is impossible to terminate a thread while waiting for a new element in the queue, because the interrupt flag is never restored:

1. The thread running the code was interrupted.

The 2.BlockingQueue # poll () method throws an InterruptedException exception and clears the break flag.

The loop condition in 3.while (! Thread.currentThread (). IsInterrupted ()) is judged to be true because the tag has been cleared.

To prevent this behavior, when a method is thrown explicitly (by declaring InterruptedException) or implicitly (by declaring / throwing a raw exception), the InterruptedException exception is always caught and the interrupt flag is restored.

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;}} above is all the content of the article "how java catches InterruptedException errors". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Errors codes flags articles content methods threads primitive not so much elements most more conditions tags fragments knowledge industry behavior information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Linux vpn Huawei Docker