Module jtrim.concurrent
Package org.jtrim2.cancel
package org.jtrim2.cancel
Defines classes and interface related to canceling tasks or other operations.
The Java way
In most Java classes, waiting for a specific task or operation can be canceled using thread interrupts. Using thread interrupts however is not easy to done right and as such is error prone. In fact many (even respected) libraries hide thrownInterruptedException instances and with it the
interrupted status of a thread. Note that the
java.util.concurrent.FutureTask class is prone to interrupt another
task running on the same thread later. Theoretically it is also possible
(but requires an extremely unlucky thread scheduling) that canceling a task
of java.util.concurrent.ThreadPoolExecutor will cause another task of
the ThreadPoolExecutor to be interrupted. Since even the classes in
the core library of Java is prone to such errors, it signifies the problems
using thread interruption.
The main problem with thread interruption is that it is effectively a global variable which is almost completely public to anyone. This makes it hard to rely on thread interrupts as anyone who has access to the thread (and every task running on them. Another problem is that one cannot be notified of thread interrupts asynchronously. The interrupted status of a thread can only be polled causing an inherent limitation.
Cancellation in JTrim
JTrim classes employ a way of canceling tasks or operations very similar to .NET 4. That is, cancellation can be detected through aCancellationToken. This CancellationToken
can be controlled (i.e.: be canceled) by a
CancellationController. See those classes for
further details on how exactly.
Since there are many useful classes in Java already relying on thread
interruptions, the CancelableWaits helper class was
created to provide static helper methods to convert waiting for thread
interrupts to waiting for CancellationToken.
- See Also:
-
ClassDescriptionDefines static helper methods to wait for a cancellation request instead of thread interruption.Contains static helper methods and fields related cancellation.Defines an interface to cancel an asynchronously executing task.Defines an interface for linked
CancellationControllerandCancellationTokenobjects.Defines an interface to detect cancellation requests.Defines a generic interface to wait for an event to occur or return before the given timeout elapses.InterruptibleTask<ResultType>Defines a generic task which can be canceled by interrupting the thread executing the task.Defines a generic interface to wait for an event to occur.Thrown by tasks when they detect that they were requested to be canceled.Defines an exception for when an operation was canceled due to timing out.Defines aListenerRefwhich can be used to unregister the associated listener and wait until it can be ensured that the listener is not going to be executed anymore.