Lightweight Java implementation of an operation cancellation mechanism, similar to C#'s CancellationToken. Designed to be minimal, composable, and runtime-agnostic — works well with standard Java concurrency tools and third-party frameworks.
To use this library, you will need:
- Java 11 or higher
- Maven or Gradle
- Immutable, thread-safe
CancelTokenabstraction - Simple and lightweight cancellation source (
CancelSource) - Composable tokens (linked or combined)
- Integration with
CompletableFutureand any asynchronous workflows - Memory-friendly:
CancelSourcesupports reuse viareset()
dependencies {
implementation group: 'com.github.romanqed', name: 'jct', version: '1.2.1'
}<dependencies>
<dependency>
<groupId>com.github.romanqed</groupId>
<artifactId>jct</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>CancelSource source = Cancellation.source();
CancelToken token = source.token();
CompletableFuture<Void> future = token.onCancelled().thenRun(() -> {
System.out.println("Cancelled!");
});
// Later:
source.cancel();CancelToken token1 = Cancellation.source().token();
CancelToken token2 = Cancellation.source().token();
CancelToken combined = Cancellation.combinedToken(token1, token2);
combined.onCancelled().thenRun(() -> {
System.out.println("Any of the tokens was cancelled");
});CancelSource source = Cancellation.source();
// Use source.token() in one task
runCancellableTask(source.token());
// Cancel and reset
source.cancel();
source.reset();
// Reuse for another task
runCancellableTask(source.token());CancelToken empty = Cancellation.emptyToken();
empty.onCancelled().thenRun(() -> {
// Will never be invoked
});- Gradle - Dependency management
- RomanQed - Main work
See also the list of contributors who participated in this project.
This project is licensed under the Apache License 2.0 - see the LICENSE file for details