ExecutorService 0.5.0
See the version list below for details.
dotnet add package ExecutorService --version 0.5.0
NuGet\Install-Package ExecutorService -Version 0.5.0
<PackageReference Include="ExecutorService" Version="0.5.0" />
<PackageVersion Include="ExecutorService" Version="0.5.0" />
<PackageReference Include="ExecutorService" />
paket add ExecutorService --version 0.5.0
#r "nuget: ExecutorService, 0.5.0"
#:package ExecutorService@0.5.0
#addin nuget:?package=ExecutorService&version=0.5.0
#tool nuget:?package=ExecutorService&version=0.5.0
ExecutorService
A .NET port of Java's
java.util.concurrent.ExecutorService:
fixed-size pools of dedicated threads, an explicit lifecycle (Shutdown, ShutdownNow,
AwaitTermination), and Task-based futures.
Why?
The .NET ThreadPool is a single, process-wide, elastic pool. That is the right default for async I/O, but sometimes
you want what Java developers reach for with Executors.newFixedThreadPool(n):
- A fixed number of threads for a specific workload, isolated from the rest of the process.
- Safe blocking work without starving the shared pool.
- A deterministic shutdown: stop accepting work, drain or drop the queue, wait for termination.
- Strict FIFO and, with one thread, strictly sequential execution.
Installation
dotnet add package ExecutorService
Targets .NET 8 and .NET 10, with no dependencies on either.
Quick start
using ExecutorService;
using IExecutorService executor = Executors.NewFixedThreadPool(4);
// Fire and forget
executor.Execute(() => Console.WriteLine("hello from a pool thread"));
// Submit and await a result
Task<int> future = executor.Submit(() => ComputeSomethingExpensive());
int result = await future;
// Orderly shutdown: finish queued work, reject new work
executor.Shutdown();
bool terminated = executor.AwaitTermination(TimeSpan.FromSeconds(10));
Disposing the executor is equivalent to Java's close(): it calls Shutdown() and waits for termination.
await using does the same without blocking.
Dropping pending work
IReadOnlyList<Task> neverStarted = executor.ShutdownNow();
// each Task in `neverStarted` is in the Canceled state
Tasks that are already running are not interrupted, because .NET has no thread interruption. They can stop
cooperatively by observing ShutdownToken, which ShutdownNow() cancels:
var executor = Executors.NewFixedThreadPool(4);
executor.Submit(() =>
{
while (!executor.ShutdownToken.IsCancellationRequested)
{
ProcessNextBatch();
}
executor.ShutdownToken.ThrowIfCancellationRequested(); // the Task ends up Canceled
});
The graceful Shutdown() never cancels that token: queued tasks are allowed to finish.
Configuring worker threads
var executor = Executors.NewFixedThreadPool(2, new ThreadPoolExecutorOptions
{
ThreadNamePrefix = "image-resizer", // threads are named image-resizer-0, image-resizer-1
IsBackground = false, // keep the process alive while work is pending
Priority = ThreadPriority.BelowNormal,
});
Metrics
The executor publishes metrics through System.Diagnostics.Metrics, the in-box OpenTelemetry metrics API.
No extra package reference is needed — and none is imposed on you: this library takes no dependency on any
telemetry SDK, so your application picks the exporter.
builder.Services.AddOpenTelemetry()
.WithMetrics(metrics => metrics.AddMeter(ThreadPoolExecutor.MeterName));
That is all it takes to reach Prometheus / Grafana, Azure Monitor, or any OTLP backend such as New Relic, Datadog or Honeycomb. To look without any pipeline at all:
dotnet-counters monitor --process-id <pid> --counters ExecutorService
| Instrument | Kind | Unit | Meaning |
|---|---|---|---|
executor.tasks.queued |
Gauge | {task} |
Tasks waiting to be executed |
executor.threads |
Gauge | {thread} |
Worker threads owned by the executor |
executor.tasks.submitted |
Counter | {task} |
Tasks accepted for execution |
executor.tasks.completed |
Counter | {task} |
Terminal tasks, tagged by outcome |
executor.tasks.rejected |
Counter | {task} |
Submissions refused after shutdown |
executor.task.queue.duration |
Histogram | s |
Time a task waited in the queue before starting |
executor.task.execution.duration |
Histogram | s |
Time a task spent executing |
Every measurement carries an executor.name tag, taken from ThreadNamePrefix, so several executors in one
process stay apart. executor.tasks.completed adds executor.task.status with success, faulted or
canceled.
Watch executor.task.queue.duration above all: a fixed pool over an unbounded queue absorbs overload silently,
and queue latency is what tells you the pool is undersized before anything downstream times out.
Histograms are only timestamped while something is listening, so the cost of leaving metrics unobserved is one boolean read per task. To scope metrics to a dependency injection container, hand the executor a meter of your own:
new ThreadPoolExecutorOptions { Meter = meterFactory.Create(ThreadPoolExecutor.MeterName) }
A supplied meter is never disposed by the executor; the one it creates for itself is released when it terminates.
Java to .NET mapping
| Java | ExecutorService (.NET) |
|---|---|
Executor |
IExecutor |
ExecutorService |
IExecutorService |
Executors.newFixedThreadPool(n) |
Executors.NewFixedThreadPool(n) |
Executors.newSingleThreadExecutor() |
Executors.NewSingleThreadExecutor() |
execute(Runnable) |
Execute(Action) |
submit(Runnable) / submit(Callable) |
Submit(Action) / Submit<T>(Func<T>) |
Future<T> |
Task<T> |
shutdown() / shutdownNow() |
Shutdown() / ShutdownNow() |
awaitTermination(timeout, unit) |
AwaitTermination(TimeSpan) / AwaitTerminationAsync(TimeSpan, CancellationToken) |
isShutdown() / isTerminated() |
IsShutdown / IsTerminated |
close() |
Dispose() / DisposeAsync() |
RejectedExecutionException |
RejectedExecutionException |
Roadmap
See CHANGELOG.md for released features. Planned:
InvokeAll/InvokeAny- Cancellation-aware overloads (
Action<CancellationToken>,Func<CancellationToken, T>) - Async task overloads (
Func<Task>,Func<Task<T>>) - Bounded queues with rejection policies (
Abort,CallerRuns,Discard,DiscardOldest) Executors.NewCachedThreadPool()with core / max pool size and keep-aliveIScheduledExecutorService(Schedule,ScheduleAtFixedRate,ScheduleWithFixedDelay)TaskScheduleradapter soTask.Factory.StartNewcan target an executor
Contributing
Contributions are welcome. Please read CONTRIBUTING.md and the Code of Conduct.
License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.