8000 GitHub - jinganix/peashooter: Call tasks sequentially and prevent deadlocks · GitHub
[go: up one dir, main page]

Skip to content

About

Call tasks sequentially and prevent deadlocks

Topics

Resources

Contributing

Stars

3 stars

Watchers

1 watching

Forks

Repository files navigation

CI Coverage License

中文版本

peashooter

peashooter is a lightweight Java library for per-key ordered task execution on thread pools (sometimes called a keyed serial executor or ordered executor): tasks sharing the same key run one after another in submission order, while different keys run in parallel on a shared pool — sequential guarantees without global locking, plus nested synchronous calls that avoid self-deadlock.

AI-friendly summary: see llms.txt for canonical facts, API summary, and FAQ in LLM-citable form.

Contents

Features

  • Ordered execution per key — tasks sharing the same key run one after another, in submission order.
  • Concurrent across keys — different keys use the shared thread pool in parallel.
  • Deadlock-safe nesting — supply / executeSync detect re-entrant calls on the same key and run inline instead of blocking (fail fast when same-key peers are already queued).
  • Distributed tracing — built-in trace IDs and parent/child spans for ordered call chains.
  • Low overhead — lock-free hot path during task execution; per-key queues use Caffeine with idle expiration.

When to use

Use peashooter when you need per-entity serialization on a shared pool:

  • per-user / per-account request ordering (e.g. balance updates for the same user must not race);
  • per-aggregate ordering in DDD / event-driven systems (events for one aggregate applied in order);
  • per-device / per-session message processing in gateways and IM systems;
  • replacing a fragile "one thread per key" or synchronized map-of-locks design.

Not for: global total ordering across all keys (use a single queue), strict real-time scheduling, or distributed (multi-process) ordering — peashooter orders within one JVM; cross-process ordering needs a distributed lock or queue.

Requirements

  • Java 21+

Installation

Maven

<dependency>
  <groupId>io.github.jinganix.peashooter</groupId>
  <artifactId>peashooter</artifactId>
  <version>0.0.14</version>
</dependency>

Gradle (Groovy)

implementation 'io.github.jinganix.peashooter:peashooter:0.0.14'

Gradle (Kotlin)

implementation("io.github.jinganix.peashooter:peashooter:0.0.14")

Quick start

ExecutorService pool = Executors.newFixedThreadPool(8);
OrderedTraceExecutor executor = new OrderedTraceExecutor(pool);

// Same-key tasks run serially, but use a synchronized container: callers mixing
// keys or reading from another thread still need a thread-safe collection.
List<String> values = Collections.synchronizedList(new ArrayList<>());
executor.executeAsync("user-1", () -> values.add("1"));
executor.supply("user-1", () -> { values.add("2"); return null; });
executor.executeAsync("user-1", () -> values.add("3"));
executor.executeSync("user-1", () -> values.add("4"));

// Submission order is preserved: [1, 2, 3, 4]
System.out.println("Values: [" + String.join(", ", values) + "]");

How it works

Per-key ordering

OrderedTraceExecutor maintains one TaskQueue per key. Submitters take a short lock to enqueue work; the worker runs tasks for that key strictly in FIFO order.

When three tasks are submitted sequentially for the same key:

executor.executeAsync("foo", task1);  // L1
executor.executeAsync("foo", task2);  // L2
executor.executeAsync("foo", task3);  // L3

Execution for key "foo" follows enqueue order — task1 → task2 → task3. Later tasks never start until the previous one finishes. Concurrent submissions from different threads still run in the order they reach the queue, not in source-code order.

Different keys are independent — "foo" and "bar" can run at the same time on the pool.

Nested synchronous calls

Nested synchronous calls on different keys are scheduled through the same mechanism. The inner supply runs on the correct queue, and the queue monitor is never held across the nested call — but the outer key's runner (and the thread waiting for the inner call) stay busy until it completes:

int value =
    executor.supply(
        "bar",
        () ->
            executor.supply(
                "foo", () -> executor.supply("bar", () -> 1)));
// value == 1

Re-entrant synchronous calls on the same key are detected via the current trace span and execute inline when no peer tasks are queued for that key, so they cannot deadlock waiting on themselves. If same-key peers are already queued, such a nested call fails fast with IllegalStateException instead of overtaking them (submission order is never silently broken): restructure the call so the nested same-key work runs before peers are waiting. Multi-key overloads (executeSync(keys, …), supply(keys, …)) that de-duplicate to two or more distinct keys always enqueue each level, because their global sorted acquisition order must hold; a collection that de-duplicates to one key takes the single-key path above.

Cross-key nesting order matters. A nested executeSync / supply holds the outer key and one pool thread while it waits for the inner key, so nested single-key calls acquire keys in call order, not sorted order. Two concurrent chains that nest in opposite orders (a → b and b → a) can deadlock each other until the sync timeout fires. The multi-key overloads are immune because they sort and de-duplicate every key they hold. Route cross-key work through the multi-key overloads, or acquire nested cross-key syncs in one global order (for example ascending) on every thread, and size the pool for at least one thread per concurrently blocked nesting level.

API

Method Description
executeAsync(key, task) Enqueue task for key; returns without waiting with a pool-backed executor. With a synchronous executor such as DirectExecutor it may run the task inline and block when it claims an idle queue; if another runner is active for the key it enqueues behind it and returns.
submitAsync(key, task) / supplyAsync(key, supplier) Enqueue for key; return a future completed after the task runs.
supplyCheckedAsync(key, supplier) / supplyCheckedAsync(keys, type, supplier) Async variants propagating the declared checked failure via the future.
executeSync(key, task) Run task on the queue for key and block until it completes (default timeout 10 seconds).
executeSync(keys, task) Sort keys in natural String order, de-duplicate, then acquire outermost-first and run task.
supply(key, supplier) Like executeSync, but returns the supplier result.
supply(keys, supplier) Multi-key variant of supply with the same sorted acquisition.
supplyChecked(key, type, supplier) / supplyChecked(keys, type, supplier) Sync variants propagating the declared checked failure unwrapped.
submitAsync(keys, task) / supplyAsync(keys, supplier) Async multi-key variants with the same sorted acquisition.
isIdle(key) Whether no tasks are queued and no runner is in flight for key.
getReentrantInlineCount() Cumulative peer-free nested same-key sync executions run inline.
builder(executor) Builder for custom queues, selector, tracer, pool sizing, and timeout.
setTimeout(Duration) / getTimeout() Configure / read the timeout for synchronous waits and for each inner level of a multi-key async chain.
getTracer() Access the tracer for custom span integration.

Async submissions are fail-fast for the outermost submission: when the queue's executor rejects the work before it runs, the failure propagates to the calling thread, so executeAsync throws and submitAsync / supplyAsync / supplyCheckedAsync throw instead of returning their future (deduplicate retries via the key). The future-returning methods contain an outermost selector Exception instead: their submission future is completed exceptionally and returned. Rejections at inner multi-key levels never reach the submitting thread: they complete the returned future and are forwarded directly to a RejectionAware task.

Advanced wiring is available via constructors that accept a custom TaskQueueProvider, ExecutorSelector, and Tracer.

Comparison with alternatives

Approach Ordering guarantee Parallelism Nested-call safety
synchronized / ReentrantLock per key Manual — easy to get wrong (lock map leaks, lock ordering) Pool threads block on locks Self-deadlock unless re-entrant and carefully ordered
One single-thread executor per key FIFO per key Unbounded thread growth with many keys Cross-executor nesting can deadlock
Global lock / single queue Total order (stronger than needed) None — one task at a time Deadlock-prone
peashooter FIFO per key, enforced by the queue Shared pool, parallel across keys Same-key re-entry runs inline; multi-key sorted acquisition

FAQ

Is peashooter a thread pool? No. It orders work on top of your own ExecutorService — you keep full control of pool sizing, rejection, and lifecycle.

Does submission order hold across threads? Execution follows the order tasks reach the queue, not source-code order. Single-threaded submission preserves program order exactly.

What happens on same-key nested sync when peers are queued? It throws IllegalStateException instead of overtaking them. Restructure so the nested same-key work runs before peers are waiting.

How do I avoid cross-key deadlocks? Acquire nested cross-key syncs in one global order (e.g. ascending) on every thread, or use the multi-key overloads (supply(keys, …)), which sort and de-duplicate keys for you. Size the pool for at least one thread per concurrently blocked nesting level.

Do I still need thread-safe collections? Yes. peashooter orders tasks; it does not make your data structures thread-safe when keys are mixed or reads happen off the queue thread.

What is the default sync timeout? 10 seconds, configurable via setTimeout(Duration) or the builder.

Benchmarks

⚠️ The tables below are single-run illustrations (n=1) on Apple M1 Pro (10 cores, 16 GB RAM, JDK 21 G1). They are allocation- and GC-sensitive: samples taken in one run have differed by ~2x on the same host. Do not quote them as guarantees — please re-run locally for your hardware with:

./gradlew :lib:test --tests "*Benchmark*"

TaskQueue (source)

5,000,000 counter increments, single-threaded queue drain (1 warm-up + 3 timed runs, reporting P95; see test). Single-run illustration only (n=1, M1 Pro) — please re-run locally:

Implementation Time (n=1, M1 Pro, illustrative — re-run locally)
TaskQueue ~620 ms
synchronized ~2336 ms
ReentrantLock ~2412 ms

The baselines push every increment through the same 8-thread pool and serialize only the counter body on the lock, while TaskQueue drains one key on a single runner: both execute the 5,000,000 increments, but strict per-key ordering forfeits the pool's parallelism. The table therefore shows end-to-end drain latency under the ordering guarantee, not per-operation overhead — expect TaskQueue and the baselines to land within the same order of magnitude.

The benchmark reports P95 over 3 timed runs against both baselines and logs a WARN when P95 reaches >= 2x of either one. Throughput is a triage signal, not a hard wall-clock gate: a strict gate flakes on loaded CI hardware, so re-run locally and treat a sustained ~2x slowdown as a regression to investigate.

Redis lockable queue (source)

500 tasks (requires Redis; see test setup, n=1, M1 Pro):

Implementation Time (n=1)
RedisLockableTaskQueue ~84 ms
Per-task Redis lock ~1268 ms

Contributing

See CONTRIBUTING.md for how to report issues, run tests, and submit changes.

./gradlew build

About

Call tasks sequentially and prevent deadlocks

Topics

Resources

Contributing

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

0