Class Task<T>
- Type Parameters:
T- the type of result produced by the task
- All Implemented Interfaces:
Awaitable<T>
DefaultContext.
Each Task wraps a FutureTask internally and runs in a CleanableThread,
which can optionally execute a cleanup action after the task completes.
Key features:
- Execution within a specific
DefaultContext, preserving thread-local context. - Optional cleaner
Runnableexecuted when the task completes. - Lifecycle management: spawning, awaiting, checking completion, cancelling, and timeout-based retrieval.
Usage example:
DefaultContext ctx = DefaultContext.getCurrentContext();
Task<String> task = Task.of(ctx, () -> "Hello", () -> System.out.println("Cleaning up"));
task.spawn();
String result = task.await();
- Author:
- Chakib Daii
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final Supplier<CleanableThread>private final DefaultContextprivate FutureTask<T>private final longprivate Thread -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivateTask(DefaultContext context, Supplier<T> supplier, Runnable cleaner) Constructs a new Task for the given context, supplier, and cleaner. -
Method Summary
Modifier and TypeMethodDescriptionawait()Blocks until the task completes and returns the result.booleancancel(boolean mayInterruptIfRunning) Attempts to cancel the task.private voidChecks whether this task has been spawned.Retrieves the task result, blocking up to the specified timeout.Returns the context in which this task runs.longReturns the unique identifier of this task.Returns the underlying thread of this task.booleanisAlive()Checks whether the task's thread is alive.booleanChecks if the task was cancelled.booleanisDone()Checks if the task has completed.voidjoin()Waits for the task thread to terminate.static <T> Task<T>of(DefaultContext context, Supplier<T> supplier, Runnable cleaner) Creates a new Task instance.voidspawn()Spawns the task in a new thread.voidstop()Stops this task gracefully by setting the running flag to false and interrupting its thread.toString()Returns a string representation of this Task.
-
Field Details
-
taskId
private final long taskId -
context
-
callable
-
cleanableThreadSupplier
-
thread
-
future
-
-
Constructor Details
-
Task
Constructs a new Task for the given context, supplier, and cleaner.- Parameters:
context- the execution context for this tasksupplier- the supplier that produces the task resultcleaner- optional cleanup code executed after task completion
-
-
Method Details
-
of
Creates a new Task instance.- Type Parameters:
T- result type- Parameters:
context- the execution contextsupplier- the task logiccleaner- optional cleaner for post-completion- Returns:
- a new Task
-
spawn
public void spawn()Spawns the task in a new thread.- Throws:
NaftahBugError- if the task has already been spawned
-
await
Blocks until the task completes and returns the result.- Specified by:
awaitin interfaceAwaitable<T>- Returns:
- the result of the task
- Throws:
Exception- if the task throws an exceptionIllegalStateException- if the task has not been spawnedNaftahBugError- if the computation throws an exception during execution
-
isDone
public boolean isDone()Checks if the task has completed.- Returns:
- true if the task is done
- Throws:
IllegalStateException- if the task has not been spawned
-
isCancelled
public boolean isCancelled()Checks if the task was cancelled.- Returns:
- true if the task was cancelled
- Throws:
IllegalStateException- if the task has not been spawned
-
cancel
public boolean cancel(boolean mayInterruptIfRunning) Attempts to cancel the task.- Parameters:
mayInterruptIfRunning- true if the thread executing the task should be interrupted- Returns:
- true if the task was successfully cancelled
- Throws:
IllegalStateException- if the task has not been spawned
-
get
Retrieves the task result, blocking up to the specified timeout.- Parameters:
timeout- the maximum time to waitunit- the time unit of the timeout- Returns:
- the task result
- Throws:
Exception- if the task throws an exceptionIllegalStateException- if the task has not been spawned
-
checkSpawned
private void checkSpawned()Checks whether this task has been spawned.A task is considered "spawned" once
spawn()has been called, which creates the internalFutureTaskand starts its execution in a thread.If this method detects that the task has not yet been spawned, it throws an
IllegalStateExceptionto prevent operations that require the task to exist (such asawait(),isDone(),get(long, TimeUnit), orcancel(boolean)).- Throws:
NaftahBugError- if the task has not been spawned yet
-
getContext
Returns the context in which this task runs.- Returns:
- the execution context
-
getTaskId
public long getTaskId()Returns the unique identifier of this task.Each task is assigned a unique ID at creation time, which can be used for logging, debugging, monitoring, or distinguishing between multiple tasks running concurrently.
- Returns:
- the unique task ID
-
stop
public void stop()Stops this task gracefully by setting the running flag to false and interrupting its thread. -
join
Waits for the task thread to terminate.- Throws:
InterruptedException- if interrupted while waiting
-
isAlive
public boolean isAlive()Checks whether the task's thread is alive.- Returns:
- true if the thread is alive, false otherwise
-
getThread
Returns the underlying thread of this task.- Returns:
- the task's thread
-
toString
Returns a string representation of this Task.The format is "<شغل {taskId}>", where "شغل" means "Task" in Arabic and {taskId} is a unique numeric identifier for this task, converted to a string using
ObjectUtils.numberToString(Number).This representation is intended for debugging and logging purposes to easily distinguish tasks by their ID.
-