Search⌘ K
AI Features

TimeoutException

Explore how Java's TimeoutException indicates the failure of a blocking operation due to timeout, with examples from CyclicBarrier. Understand its use in concurrent programming and how it helps manage thread synchronization in Java applications.

We'll cover the following...

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

TimeoutException is used as a means to indicate that a blocking operation has timed-out. Consider the CyclicBarrier class (read about cyclic barrier here) which exposes the method await(), which takes in a timeout value. If a thread invokes this method on an object of CyclicBarrier and the barrier isn’t reached by other threads within the specified timeout by the first thread then TimeoutException is thrown and the barrier is broken. In some cases, values such as boolean can be returned to indicate timeout rather than throwing the TimeoutException.

The program in the widget below demonstrates an instance of a CyclicBarrier throwing the TimeoutException when the main thread awaits at the barrier for 100 milliseconds.

Java
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.BrokenBarrierException;
class Demonstration {
public static void main( String args[] ) throws TimeoutException, InterruptedException, BrokenBarrierException {
// create a barrier for two threads.
CyclicBarrier barrier = new CyclicBarrier(2);
// TimeoutException thrown after 100 ms elapse
barrier.await(100, TimeUnit.MILLISECONDS);
}
}

TimeoutException is a checked exception extending the Exception class and is part of the java.util.concurrent package. Some other Java classes that throw the TimeoutException are:

  • java.util.concurrent.AbstractExecutorService
  • jdk.jshell.execution.JdiInitiator
  • sun.nio.ch.PendingFuture