What is an InterruptedException in Java?
Asked Answered
N

3

0

I have seen many times in my code that I get an Interrupted Exception. How do I fix it?

Example:

for (int i = 0; i < readLimit; i++) {
    if (fileName.exists())
        return readFile(fileName);
        Thread.sleep(1000); // Here is where I get the error
    }
}
Namtar answered 8/11, 2020 at 17:25 Comment(2)
When was it thrown have you worked with concurencys?Kenelm
Can you share more details, when do you get the error? Also, paste the error's stack trace.Kienan
C
5

Since I don't know how much you know about Java, how java works exactly and what's concurrency, I'll try to explain as much as possible with nearly no background information needed.


At first we're going to take a look at Oracle's documentation of the InterruptedException.

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. [...]


What does this mean?

Before answering this question you have to rudimentary understand how a Thread works.

A thread is originally just a piece of code that can be managed seperately from other threads. It can run at the same time (see concurrency), run scheduled, etc.


Example

If you start a normal java program the main() method is created in an own thread 1. Everything you do will be executed in this thread. Every class you create, every method you call and basically everything that originated from main().

But if you create a Thread, it runs in an own thread 2. Everything you do in the run() method will be executed in thread 2.


What happens if you create a new Thread?

The join() method is called.

The join() method starts the thread and run() is being executed.

There's not only the join() method with no parameters but also a join(long millis) with a parameter.


When and why is it thrown?

As Rahul Iyer already said there's a variety of reasons. I'm picking some of them to get you a feeling when they're called.

  1. Timeout

The InterruptedException can be indeed thrown when a timeout was exceeded. This happens when the join(long millis) is called. The parameter specifies that the thread can run for the given amount of milliseconds. When the thread exceeds this timeout it is interrupted. source (from line 769 to line 822).

  1. OS is stopping the thread

Maybe the Operating System (Windows, Linux, Android, etc.) decided to stop the program. Why? To free resources, your program was mistaken as a virus, hardware is shutting down, the user manually closed it, etc.

  1. An InterruptedException is thrown in the Thread

    For example you're connected to the internet and you're reading something and the internet disconnects suddenly.

  2. interrupt() is called

    As already mentioned, an InterruptedException is also thrown, when you call the interrupt() on any Thread (quite logical).


How to handle it?

You can/should handle it like every other exception. Wrap it in a try and catch, declare that the method throws it, log it, etc.

This may be the best resource for you: Handling InterruptedException in Java.

Cartography answered 4/1, 2021 at 13:32 Comment(1)
This is really nice entry-level explanation of how threads work.Disaster
A
3

From the docs: https://docs.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html

public class InterruptedException extends Exception

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:

if (Thread.interrupted())  // Clears interrupted status!
      throw new InterruptedException();

You can follow oracles tutorial here:

https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

The way to fix it is probably to surround the code that causes it with a Try-Catch block and handle the exception. For example (from Oracles tutorial):

for (int i = 0; i < importantInfo.length; i++) {
    // Pause for 4 seconds
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {
        // We've been interrupted: no more messages.
        return;
    }
    // Print a message
    System.out.println(importantInfo[i]);
}

There are more examples in the above link on how to handle different scenarios.

Advisee answered 2/1, 2021 at 6:55 Comment(2)
So is it like a timeout?Namtar
@CoolorFool-SRS - No it is not a timeout. A thread can be interrupted for a variety of reasons. I would suggest reading up about concurrency, threading etc, as it should answer all your questions.Advisee
H
1

Shortly, InterruptedException is usually thrown when a thread or some other action is interrupted. It does not matter if the thread was doing something or sleeping, you can programmatically do this by calling interrupt() or other methods on and "occupied" thread, who is for sleeping.

Hexone answered 4/1, 2021 at 20:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.