- 1AclNotFoundException in Java
- 2ActivationException in Java
- 3AlreadyBoundException in Java
- 4ApplicationException in Java
- 5AWTException in Java
- 6BackingStoreException in Java
- 7BadAttributeValueExpException in Java
- 8BadBinaryOpValueExpException in Java
- 9BadLocationException in Java
- 10BadStringOperationException in Java
- 11BrokenBarrierException in Java
- 12CertificateException in Java
- 13CloneNotSupportedException in Java
- 14DataFormatException in Java
- 15DatatypeConfigurationException in Java
- 16DestroyFailedException in Java
- 17ExecutionException in Java
- 18ExpandVetoException in Java
- 19FontFormatException in Java
- 20GeneralSecurityException in Java
- 21GSSException in Java
- 22IllegalClassFormatException in Java
- 23InterruptedException in Java
- 24IntrospectionException in Java
- 25InvalidApplicationException in Java
- 26InvalidMidiDataException in Java
- 27InvalidPreferencesFormatException in Java
- 28InvalidTargetObjectTypeException in Java
- 29IOException in Java
- 30JAXBException in Java
- 31JMException in Java
- 32KeySelectorException in Java
- 33LambdaConversionException in Java
- 34LastOwnerException in Java
- 35LineUnavailableException in Java
- 36MarshalException in Java
- 37MidiUnavailableException in Java
- 38MimeTypeParseException in Java
- 39NamingException in Java
- 40NoninvertibleTransformException in Java
- 41NotBoundException in Java
- 42NotOwnerException in Java
- 43ParseException in Java
- 44ParserConfigurationException in Java
- 45PrinterException in Java
- 46PrintException in Java
- 47PrivilegedActionException in Java
- 48PropertyVetoException in Java
- 49ReflectiveOperationException in Java
- 50RefreshFailedException in Java
- 51RemarshalException in Java
- 52RuntimeException in Java
- 53SAXException in Java
- 54Java ScriptException
- 55Java ServerNotActiveException
- 56Java SOAPException
- 57Java SQLException
- 58Java TimeoutException
- 59Java TooManyListenersException
- 60Java TransformerException
- 61Java TransformException
- 62Java UnmodifiableClassException
- 63Java UnsupportedAudioFileException
- 64Java UnsupportedCallbackException
- 65Java UnsupportedFlavorException
- 66Java UnsupportedLookAndFeelException
- 67Java URIReferenceException
- 68Java URISyntaxException
- 69Java UserException – Custom Exceptions with Examples
- 70Java XAException
- 71Java XMLParseException – XML Parsing and Exception Handling
- 72Java XMLSignatureException
- 73Java XMLStreamException – StAX Parsing Examples
- 74Java XPathException – Complete Guide with Examples
InterruptedException in Java
What is InterruptedException in Java?
InterruptedException
is a checked exception in Java that occurs when a thread is interrupted while it’s waiting, sleeping, or otherwise paused. It belongs to the java.lang
package and plays a crucial role in Java’s concurrency model by allowing threads to be gracefully stopped or signaled to stop.
If you've ever worked with Thread.sleep()
, wait()
, join()
, or blocking queues — you've touched areas that can throw InterruptedException
. This exception is Java’s way of saying, “Hey, this thread should stop waiting and resume.”
Why Does InterruptedException Matter?
In a multithreaded environment, sometimes a thread must be asked to pause or terminate early — perhaps due to a user request, shutdown signal, or timeout. InterruptedException
allows one thread to signal another that it should stop waiting and potentially terminate its execution.
When is InterruptedException Thrown?
Common situations where this exception is thrown:
- Calling
Thread.sleep()
- Waiting on an object using
Object.wait()
- Joining another thread with
Thread.join()
- Blocking on classes like
BlockingQueue.take()
orSemaphore.acquire()
Class Definition
package java.lang;
public class InterruptedException extends Exception {
public InterruptedException()
public InterruptedException(String message)
}
Basic Example: Sleeping Thread
This is a beginner-friendly example using Thread.sleep()
that demonstrates how InterruptedException
is triggered.
public class SleepExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
System.out.println("Thread sleeping for 5 seconds...");
Thread.sleep(5000); // attempt to sleep
System.out.println("Thread woke up naturally.");
} catch (InterruptedException e) {
System.out.println("Thread was interrupted!");
}
});
thread.start();
try {
Thread.sleep(2000); // main thread sleeps for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt(); // interrupt the sleeping thread
}
}
Thread sleeping for 5 seconds...
Thread was interrupted!
Step-by-Step Breakdown
- We start a thread that calls
Thread.sleep(5000)
. - The main thread sleeps for 2 seconds and then calls
thread.interrupt()
. - The sleeping thread catches the
InterruptedException
and prints a message.
How to Handle InterruptedException Properly
Here are three ways to handle this exception:
- Swallow it: Not recommended unless truly benign.
try { Thread.sleep(1000); } catch (InterruptedException e) { // ignored — not ideal }
- Log and exit the thread: Good for most use-cases.
catch (InterruptedException e) { System.out.println("Thread interrupted, exiting..."); return; }
- Restore the interrupt status: Best for propagating interruption upwards.
catch (InterruptedException e) { Thread.currentThread().interrupt(); // re-interrupt }
Example: Producer-Consumer with BlockingQueue
Let’s look at a more practical example where a consumer thread uses a BlockingQueue
. If the thread is interrupted while waiting to take an item, an InterruptedException
is thrown.
import java.util.concurrent.*;
public class QueueExample {
public static void main(String[] args) {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
Thread consumer = new Thread(() -> {
try {
while (true) {
String item = queue.take(); // blocks if empty
System.out.println("Consumed: " + item);
}
} catch (InterruptedException e) {
System.out.println("Consumer interrupted, shutting down.");
}
});
consumer.start();
try {
queue.put("apple");
queue.put("banana");
Thread.sleep(2000);
consumer.interrupt(); // signal consumer to stop
} catch (Exception e) {
e.printStackTrace();
}
}
}
Consumed: apple
Consumed: banana
Consumer interrupted, shutting down.
Best Practices for InterruptedException
- Always catch it — it's a checked exception.
- Restore the interrupt status when you want higher-level handlers to be aware.
- Never silently swallow it unless you have a very specific reason.
- Use try-catch blocks consistently around blocking calls.
- Interrupt long-running loops or waiting threads gracefully using
Thread.interrupt()
.
Using Loops with Interruption
It’s common to use a while-loop that checks the thread’s interrupt status like this:
while (!Thread.currentThread().isInterrupted()) {
// do work
}
This approach gives the thread a way to exit gracefully if someone calls interrupt()
on it.
Common Misconceptions
- “InterruptedException means something went wrong.” Not always. It often just means someone wants the thread to stop what it’s doing.
- “Ignoring it is okay.” Generally not. Ignoring it can cause your app to become unresponsive.
Summary
InterruptedException
is a vital part of Java’s multithreading model. It enables graceful cancellation and cleanup of threads engaged in blocking operations. From simple sleep timers to complex producer-consumer models, this exception keeps your threads cooperative and responsive.
To build robust multithreaded apps, understand not just how to catch this exception — but how to design systems around it. Respect the interrupt signal. Communicate it. Respond to it.
Comments
Loading comments...