Class InterruptTimer
Classes can use this to trip an alarm interrupting the calling thread if it doesn't complete a block within the specified timeout. Typical calling pattern is:
private InterruptTimer myTimer = ...; void foo() { try { myTimer.begin(timeout); // work } finally { myTimer.end(); } }
An InterruptTimer is not recursive. To implement recursive timers, independent InterruptTimer instances are required. A single InterruptTimer may be shared between objects which won't recursively call each other.
Each InterruptTimer spawns one background thread to sleep the specified time
and interrupt the thread which called begin(int)
. It is up to the
caller to ensure that the operations within the work block between the
matched begin and end calls tests the interrupt flag (most IO operations do).
To terminate the background thread, use terminate()
. If the
application fails to terminate the thread, it will (eventually) terminate
itself when the InterruptTimer instance is garbage collected.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static final class
(package private) static final class
private static final class
-
Field Summary
FieldsModifier and TypeFieldDescription(package private) final InterruptTimer.AutoKiller
private final InterruptTimer.AlarmState
private final InterruptTimer.AlarmThread
-
Constructor Summary
ConstructorsConstructorDescriptionCreate a new timer with a default thread name.InterruptTimer
(String threadName) Create a new timer to signal on interrupt on the caller. -
Method Summary
-
Field Details
-
state
-
thread
-
autoKiller
-
-
Constructor Details
-
InterruptTimer
public InterruptTimer()Create a new timer with a default thread name. -
InterruptTimer
Create a new timer to signal on interrupt on the caller.The timer thread is created in the calling thread's ThreadGroup.
- Parameters:
threadName
- name of the timer thread.
-
-
Method Details
-
begin
public void begin(int timeout) Arm the interrupt timer before entering a blocking operation.- Parameters:
timeout
- number of milliseconds before the interrupt should trigger. Must be > 0.
-
end
public void end()Disable the interrupt timer, as the operation is complete. -
terminate
public void terminate()Shutdown the timer thread, and wait for it to terminate.
-