java.lang.Object
org.daiitech.naftah.builtin.utils.concurrent.Task<T>
Type Parameters:
T - the type of result produced by the task
All Implemented Interfaces:
Awaitable<T>

public final class Task<T> extends Object implements Awaitable<T>
Represents an asynchronous task that executes within a given 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 Runnable executed 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 Details

  • Constructor Details

    • Task

      private Task(DefaultContext context, Supplier<T> supplier, Runnable cleaner)
      Constructs a new Task for the given context, supplier, and cleaner.
      Parameters:
      context - the execution context for this task
      supplier - the supplier that produces the task result
      cleaner - optional cleanup code executed after task completion
  • Method Details

    • of

      public static <T> Task<T> of(DefaultContext context, Supplier<T> supplier, Runnable cleaner)
      Creates a new Task instance.
      Type Parameters:
      T - result type
      Parameters:
      context - the execution context
      supplier - the task logic
      cleaner - 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

      public T await() throws NaftahBugError
      Blocks until the task completes and returns the result.
      Specified by:
      await in interface Awaitable<T>
      Returns:
      the result of the task
      Throws:
      Exception - if the task throws an exception
      IllegalStateException - if the task has not been spawned
      NaftahBugError - 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

      public T get(long timeout, TimeUnit unit) throws Exception
      Retrieves the task result, blocking up to the specified timeout.
      Parameters:
      timeout - the maximum time to wait
      unit - the time unit of the timeout
      Returns:
      the task result
      Throws:
      Exception - if the task throws an exception
      IllegalStateException - 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 internal FutureTask and starts its execution in a thread.

      If this method detects that the task has not yet been spawned, it throws an IllegalStateException to prevent operations that require the task to exist (such as await(), isDone(), get(long, TimeUnit), or cancel(boolean)).

      Throws:
      NaftahBugError - if the task has not been spawned yet
    • getContext

      public DefaultContext 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

      public void join() throws InterruptedException
      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

      public Thread getThread()
      Returns the underlying thread of this task.
      Returns:
      the task's thread
    • toString

      public String 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.

      Overrides:
      toString in class Object
      Returns:
      a string representation of the task