Java : TimeoutException (Thread) with Examples
TimeoutException (Java SE 23 & JDK 23) in Java with Examples.
 You will find code samples for most of the TimeoutException methods.
Summary
Exception thrown when a blocking operation times out. Blocking operations for which a timeout is specified need a means to indicate that the timeout has occurred. For many such operations it is possible to return a value that indicates timeout; when that is not possible or desirable then TimeoutException should be declared and thrown.
try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(3);
            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });
    TimeUnit.SECONDS.sleep(1);
    try {
        System.out.println("-- get start --");
        final var ret = future.get(1, TimeUnit.SECONDS);
        System.out.println("-- get end --");
        System.out.println("ret = " + ret);
    } catch (TimeoutException e) {
        System.out.println("TimeoutException!");
    }
}
// Result
// ↓
//task start
//-- get start --
//TimeoutException!
//task end
Constructors
TimeoutException ()
Constructs a TimeoutException with no specified detail message.
final var e = new TimeoutException();
System.out.println(e); // java.util.concurrent.TimeoutException
TimeoutException (String message)
Constructs a TimeoutException with the specified detail message.
final var e = new TimeoutException("abc");
System.out.println(e); // java.util.concurrent.TimeoutException: abc
System.out.println(e.getMessage()); // abc
Methods declared in Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Please see the link below.
Related posts
- API Examples 
        - BlockingQueue
- BrokenBarrierException
- Callable
- CancellationException
- ConcurrentHashMap.KeySetView
- ConcurrentLinkedDeque
- ConcurrentLinkedQueue
- ConcurrentMap
- ConcurrentModificationException
- ConcurrentSkipListSet
- Condition
- CopyOnWriteArrayList
- CopyOnWriteArraySet
- CountDownLatch
- CyclicBarrier
- Exchanger
- ExecutionException
- Executor
- ExecutorService
- Executors
- Future
- Future.State
- FutureTask
- InterruptedException
- Lock
- Runnable
- Semaphore
- Thread
- ThreadGroup
- ThreadLocal
- TimeUnit