Skip to main content
rule CX Codex

concurrency — Claude Code rule: what it checks and how to install

This Claude Code rule sets Java concurrency guidelines. It covers thread pools, locks, shared records, and other sources of concurrent access bugs.

MIT ★ 517 updated 2026-11-16

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/concurrency.md
Open on GitHub

What concurrency does

The rule guides the agent in spotting unsafe concurrency patterns in Java and suggesting safer alternatives. It rejects pools created through Executors and explicitly started threads, requires a consistent order when acquiring multiple locks, and calls for thread-safe singleton objects.

It also covers concurrent updates to the same record, atomic check-then-act operations, and loop exit conditions in high-concurrency code. For date formatting it recommends DateTimeFormatter; on JDK 7 and later, it calls for ThreadLocalRandom instead of sharing a Random. Install the rule at .claude/rules/concurrency.md.

What it helps with

  • configure thread pools with explicit limits
  • prevent deadlocks from inconsistent lock ordering
  • guard records against concurrent updates
  • make check-then-act operations atomic
  • avoid sharing Random across threads

Example prompts for the agent

  • Check this Java class for concurrency bugs.
  • Find unsafe thread and thread-pool creation in this code.
  • Review the locking and concurrent record updates.

How to install concurrency

Manually: put the files in place

.claude/rules/concurrency.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about concurrency

How do I install concurrency in Claude Code?

Add the rule file at .claude/rules/concurrency.md.

What does the concurrency rule do?

It sets guidelines for Java threads, locks, and concurrent access. Among other things, it rejects explicitly created threads and requires a consistent order for acquiring multiple locks.

What does concurrency require for dates and random numbers?

It recommends DateTimeFormatter instead of a shared SimpleDateFormat. On JDK 7 and later, use ThreadLocalRandom rather than sharing one Random across threads.

Source text

concurrency.md · MIT
# Concurrency guidelines

## Thread pool creation
**Detection mode**: semantic

**Do not create thread pools with Executors (MULT-CONC-001):**

```java
// Wrong: may cause OOM
ExecutorService executor = Executors.newFixedThreadPool(10);

// Correct: set all parameters explicitly
ThreadPoolExecutor executor = new ThreadPoolExecutor(
    10,  // corePoolSize
    20,  // maximumPoolSize
    60L, // keepAliveTime
    TimeUnit.SECONDS,
    new LinkedBlockingQueue<>(1000),
    new ThreadFactoryBuilder().setNameFormat("worker-%d").build(),
    new ThreadPoolExecutor.CallerRunsPolicy()
);
```

## SimpleDateFormat thread safety
**Detection mode**: semantic

```java
// Wrong: not thread-safe
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

// Correct option 1: ThreadLocal
private static final ThreadLocal<SimpleDateFormat> sdf = 
    ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

// Correct option 2: use Java 8 DateTimeFormatter (recommended)
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
```

## Lock ordering
**Detection mode**: semantic

**Locking multiple resources must follow a consistent order to prevent deadlocks (MULT-CONC-002):**

```java
// Wrong: may deadlock
public void transfer(Account from, Account to, int amount) {
    synchronized (from) {
        synchronized (to) {
            from.debit(amount);
            to.credit(amount);
        }
    }
}

// Correct: lock in a fixed order
public void transfer(Account from, Account to, int amount) {
    Account first = from.getId() < to.getId() ? from : to;
    Account second = from.getId() < to.getId() ? to : from;
    synchronized (first) {
        synchronized (second) {
            from.debit(amount);
            to.credit(amount);
        }
    }
}
```

## Concurrent modification
**Detection mode**: semantic

**Concurrent modification of the same record must use a lock or optimistic locking (MULT-CONC-003):**

```java
// Optimistic locking approach
@Update("UPDATE account SET balance = #{balance}, version = version + 1 WHERE id = #{id} AND version = #{version}")
int updateWithVersion(Account account);

// Retry logic (at least 3 times)
int retry = 0;
while (retry < 3) {
    Account account = accountDao.getById(id);
    int updated = accountDao.updateWithVersion(account);
    if (updated > 0) {
        break;
    }
    retry++;
}
```

## TOCTOU protection
**Detection mode**: semantic

**Check-Then-Act operations must be atomic (MULT-CONC-012):**

```java
// Wrong: non-atomic operation
if (account.getBalance() >= amount) {  // Check
    account.debit(amount);  // Act - the balance may have changed!
}

// Correct: use a database optimistic lock or distributed lock
@Update("UPDATE account SET balance = balance - #{amount} WHERE id = #{id} AND balance >= #{amount}")
int debitWithCheck(@Param("id") Long id, @Param("amount") Long amount);
```

## High-concurrency optimization
**Detection mode**: semantic

**In high-concurrency code, do not use equality checks as interruption/exit conditions (MULT-CONC-004):**

```java
// Wrong: may loop forever
while (count == 0) {
    // may never exit
}

// Correct: use a range check
while (count > 0) {
    // explicit exit condition
}
```

## Singleton thread safety
**Detection mode**: semantic

**Singleton objects must be thread-safe (MULT-CONC-005):**

```java
// Double-checked locking (requires volatile)
public class Singleton {
    private static volatile Singleton instance;
    
    private Singleton() { }
    
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
```

## Thread resources
**Detection mode**: semantic

**Thread resources must be provided through thread pools; do not create threads explicitly (MULT-CONC-007):**

```java
// Wrong
new Thread(new Runnable() {
    @Override
    public void run() { }
}).start();

// Correct
executor.execute(() -> {
    // ...
});
```

## Random in multithreaded code
**Detection mode**: semantic

**Avoid sharing Random across threads; on JDK 7+ use ThreadLocalRandom (MULT-CONC-011):**

```java
// Wrong
Random random = new Random();
int value = random.nextInt(100);

// Correct
int value = ThreadLocalRandom.current().nextInt(100);
```

© kyy-logs · MIT · kyy-logs/code-review-gate-skill

Similar IDE rules

All IDE rules for Code review and refactoring →

From the same set10

The whole set →
index The index Claude Code rule describes the built-in code review files and how the tool locates them. A project rule pack replaces the built-in pack instead of merging with it. CX Codex +1 ★ 517repo stars baseline-java The baseline-java Claude Code rule adds Java checks for security, concurrency, and exception handling. It applies during Java code review. CX Codex +1 ★ 517repo stars spring-performance spring-performance is a Claude Code rule for Spring/JPA practices and performance tuning. It guides agents working on Java code, database queries, and server settings. CX Codex +1 ★ 517repo stars spring-performance The spring-performance Claude Code rule sets Spring/JPA and performance checks. It flags issues in validation, transactions, queries, and batch operations. CX Codex +1 ★ 517repo stars exception-logging exception-logging — a rule for Claude Code that enforces Java exception handling and logging standards. Runs during code review to catch empty catch blocks, unmasked data, and missing transaction rollbacks. CX Codex +1 ★ 517repo stars naming-format The naming-format Claude Code rule sets Java naming and formatting conventions. It covers classes, methods, constants, and control flow. CX Codex +1 ★ 517repo stars testing-engineering The testing-engineering Claude Code rule sets expectations for unit tests, project structure, and dependencies. It covers application layers, exception handling, and domain models. CX Codex +1 ★ 517repo stars code-review-gate The code-review-gate Claude Code skill reviews code changes before a commit or PR merge. It gathers the diff, checks test quality, and records issues. CX Codex +1 ★ 517repo stars

Project sponsors

Companies that keep this analytics open