Class DefaultCancellationToken

java.lang.Object
com.alibaba.cloud.ai.graph.agent.tool.DefaultCancellationToken
All Implemented Interfaces:
CancellationToken

public class DefaultCancellationToken extends Object implements CancellationToken
Default implementation of CancellationToken.

This implementation is thread-safe and supports:

  • Multiple callbacks registration
  • Immediate callback execution if already cancelled when registered
  • Linking to CompletableFuture for automatic cancellation propagation

Example usage:


 DefaultCancellationToken token = new DefaultCancellationToken();

 // Register cleanup callback
 token.onCancel(() -> cleanupResources());

 // Start async operation
 CompletableFuture<String> future = tool.callAsync(args, ctx, token);

 // Cancel if needed
 token.cancel();
 
Since:
1.0.0
Author:
disaster
See Also:
  • Constructor Details

    • DefaultCancellationToken

      public DefaultCancellationToken()
  • Method Details

    • isCancelled

      public boolean isCancelled()
      Description copied from interface: CancellationToken
      Checks if cancellation has been requested.
      Specified by:
      isCancelled in interface CancellationToken
      Returns:
      true if cancelled
    • onCancel

      public void onCancel(Runnable callback)
      Description copied from interface: CancellationToken
      Registers a callback to be invoked when cancellation is requested.

      If cancellation has already been requested, the callback may be invoked immediately (implementation-dependent).

      Specified by:
      onCancel in interface CancellationToken
      Parameters:
      callback - the callback to run on cancellation
    • cancel

      public void cancel()
      Requests cancellation and notifies all registered callbacks.

      This method is idempotent - calling it multiple times has the same effect as calling it once. Callbacks are only invoked on the first call.

    • linkedTo

      public static DefaultCancellationToken linkedTo(CompletableFuture<?> future)
      Creates a cancellation token linked to a CompletableFuture. The token will be cancelled when the future is cancelled.

      Note: This creates a one-way binding. Cancelling the token does not cancel the future. To cancel the future, call future.cancel(true).

      Parameters:
      future - the future to link to
      Returns:
      a new cancellation token that will be cancelled when the future is cancelled