Get the FREE Ultimate OpenClaw Setup Guide →

125-java-concurrency

npx machina-cli add skill jabrena/cursor-rules-java/125-java-concurrency --openclaw
Files (1)
SKILL.md
4.0 KB

Java rules for Concurrency objects

Identify and apply Java concurrency best practices to improve thread safety, scalability, and maintainability by using modern java.util.concurrent utilities, virtual threads, and structured concurrency.

Core areas: Thread safety fundamentals (ConcurrentHashMap, AtomicInteger, ReentrantLock, ReadWriteLock, Java Memory Model), ExecutorService thread pool configuration (sizing, keep-alive, bounded queues, rejection policies, graceful shutdown), Producer-Consumer and Publish-Subscribe concurrent design patterns (BlockingQueue), CompletableFuture for non-blocking async composition (thenApply/thenCompose/exceptionally/orTimeout), immutability and safe publication (volatile, static initializers), lock contention and false-sharing performance optimization, virtual threads (Executors.newVirtualThreadPerTaskExecutor()) for I/O-bound scalability, StructuredTaskScope for lifecycle-scoped task management, ScopedValue over ThreadLocal for immutable cross-task data, cooperative cancellation and InterruptedException discipline, backpressure with bounded queues and CallerRunsPolicy, deadlock avoidance via global lock ordering and tryLock with timeouts, ForkJoin/parallel-stream discipline for CPU-bound work, virtual-thread pinning detection (JFR VirtualThreadPinned), thread naming and UncaughtExceptionHandler observability, and fit-for-purpose primitives (LongAdder, CopyOnWriteArrayList, StampedLock, Semaphore, CountDownLatch, Phaser).

Prerequisites: Run ./mvnw compile or mvn compile before applying any change. If compilation fails, stop immediately — compilation failure is a blocking condition that prevents any further processing.

Multi-step scope: Step 1 validates the project compiles. Step 2 analyzes existing concurrency patterns and categorizes issues by impact (CRITICAL, MAINTAINABILITY, PERFORMANCE, SCALABILITY). Step 3 applies thread safety fundamentals — replacing unsafe collections with java.util.concurrent equivalents and atomic classes. Step 4 refactors thread pool management to use properly configured ExecutorService instances with bounded queues and rejection policies. Step 5 implements concurrent design patterns (Producer-Consumer via BlockingQueue, Publish-Subscribe). Step 6 migrates asynchronous operations to CompletableFuture with proper chaining and timeout handling. Step 7 adopts modern Java concurrency features — virtual threads for I/O-bound tasks, StructuredTaskScope for related task groups, and ScopedValue instead of ThreadLocal. Step 8 enforces cancellation and interruption discipline — never swallowing InterruptedException, using Future.cancel(true), and preferring lockInterruptibly. Step 9 adds backpressure and overload protection — bounded queues, semaphores/bulkheads, and CallerRunsPolicy. Step 10 eliminates deadlock risks via lock ordering, minimized lock scope, and tryLock with timeouts. Step 11 adds observability — named threads, UncaughtExceptionHandler, JFR metrics, and structured logging. Step 12 runs ./mvnw clean verify to confirm all tests pass after changes.

Before applying changes: Read the reference for detailed good/bad examples, constraints, and safeguards for each concurrency pattern.

Reference

For detailed guidance, examples, and constraints, see references/125-java-concurrency.md.

Source

git clone https://github.com/jabrena/cursor-rules-java/blob/main/skills/125-java-concurrency/SKILL.mdView on GitHub

Overview

This skill teaches applying Java concurrency best practices across thread safety, executor management, and modern patterns. It covers core primitives, virtual threads, structured concurrency, backpressure, cancellation discipline, and observability to build safe and scalable concurrent systems.

How This Skill Works

It analyzes concurrency needs in Java projects, then guides refactors from unsafe patterns to java.util.concurrent primitives, proper ExecutorService configurations, and asynchronous flows with CompletableFuture. It also introduces modern concepts like virtual threads, StructuredTaskScope, and ScopedValue to improve maintainability and scalability.

When to Use It

  • You’re building an IO-bound service and want to leverage virtual threads for scalability.
  • You need to replace shared mutable state with safe publication and concurrent primitives.
  • You must implement producer-consumer or publish-subscribe patterns using BlockingQueue.
  • You want non-blocking async flows with CompletableFuture, including timeouts and cancellation.
  • You aim to improve observability, lifecycle management, and backpressure in concurrent systems.

Quick Start

  1. Step 1: Run ./mvnw compile (or mvn compile) to ensure the project builds baseline.
  2. Step 2: Identify hotspots with shared mutable state and replace with ConcurrentHashMap/Atomic* and bounded queues.
  3. Step 3: Introduce ExecutorService with a bounded queue, add CompletableFuture-based async paths, and switch IO-bound paths to virtual threads where appropriate.

Best Practices

  • Use ExecutorService with properly sized pools, bounded queues, and appropriate rejection policies.
  • Favor java.util.concurrent primitives (Atomic*, Concurrent*, CopyOnWrite*) over synchronized blocks where possible.
  • Prefer ScopedValue over ThreadLocal and use StructuredTaskScope for related task groups.
  • Apply cooperative cancellation and respect InterruptedException; propagate cancellation signals.
  • Enhance observability with named threads, UncaughtExceptionHandler, metrics, and structured logging.

Example Use Cases

  • High-throughput REST API backend handling large numbers of concurrent requests.
  • Data processing pipeline implementing Producer-Consumer via BlockingQueue.
  • Async service composition using CompletableFuture with proper timeouts and error handling.
  • IO-bound microservice migrated to virtual threads for better scalability.
  • Batch job runner using StructuredTaskScope to manage grouped tasks lifecycle.

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers