Package org.apache.commons.io
Class ThreadMonitor
java.lang.Object
org.apache.commons.io.ThreadMonitor
- All Implemented Interfaces:
Runnable
Monitors a thread, interrupting it if it reaches the specified timeout.
This works by sleeping until the specified timeout amount and then interrupting the thread being monitored. If the
thread being monitored completes its work before being interrupted, it should interrupt() the monitor
thread.
Duration timeout = Duration.ofSeconds(1);
try {
Thread monitor = ThreadMonitor.start(timeout);
// do some work here
ThreadMonitor.stop(monitor);
} catch (InterruptedException e) {
// timed amount was reached
}
-
Field Summary
Fields -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivateThreadMonitor(Thread thread, Duration timeout) Constructs a new monitor. -
Method Summary
Modifier and TypeMethodDescriptionvoidrun()Sleeps until the specified timeout amount and then interrupt the thread being monitored.(package private) static ThreadStarts monitoring the specified thread.(package private) static ThreadStarts monitoring the current thread.(package private) static voidStops monitoring the specified thread.
-
Field Details
-
thread
-
timeout
-
-
Constructor Details
-
ThreadMonitor
Constructs a new monitor.- Parameters:
thread- The thread to monitor.timeout- The timeout amount.
-
-
Method Details
-
start
Starts monitoring the current thread.- Parameters:
timeout- The timeout amount. or no timeout if the value is zero or less.- Returns:
- The monitor thread or
nullif the timeout amount is not greater than zero.
-
start
Starts monitoring the specified thread.- Parameters:
thread- The thread to monitortimeout- The timeout amount. or no timeout if the value is zero or less.- Returns:
- The monitor thread or
nullif the timeout amount is not greater than zero.
-
stop
Stops monitoring the specified thread.- Parameters:
thread- The monitor thread, may benull.
-
run
public void run()Sleeps until the specified timeout amount and then interrupt the thread being monitored.
-