java-concurrency

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Java Concurrency Skill

Java并发编程技能

Master Java concurrency patterns for thread-safe applications.
掌握用于线程安全应用的Java并发编程模式。

Overview

概述

This skill covers concurrency from basic threads to virtual threads (Java 21+), including thread pools, synchronization, and CompletableFuture.
本技能涵盖从基础线程到Virtual Threads(Java 21+)的并发编程内容,包括线程池、同步机制以及CompletableFuture。

When to Use This Skill

何时使用本技能

Use when you need to:
  • Write thread-safe code
  • Implement parallel processing
  • Use async programming patterns
  • Tune thread pools
  • Debug concurrency issues
当你需要以下操作时使用:
  • 编写线程安全的代码
  • 实现并行处理
  • 使用异步编程模式
  • 调优线程池
  • 调试并发问题

Topics Covered

涵盖主题

Thread Management

线程管理

  • Thread lifecycle and states
  • Daemon vs user threads
  • Interrupt handling
  • 线程生命周期与状态
  • 守护线程 vs 用户线程
  • 中断处理

Synchronization

同步机制

  • synchronized, volatile
  • Lock interfaces (ReentrantLock)
  • Atomic operations
  • synchronized、volatile
  • Lock接口(ReentrantLock)
  • 原子操作

Executors

执行器

  • ThreadPoolExecutor configuration
  • ForkJoinPool
  • Virtual Threads (Java 21+)
  • ThreadPoolExecutor配置
  • ForkJoinPool
  • Virtual Threads(Java 21+)

CompletableFuture

CompletableFuture

  • Async execution
  • Chaining and composition
  • Exception handling
  • 异步执行
  • 链式调用与组合
  • 异常处理

Quick Reference

快速参考

java
// Virtual Threads (Java 21+)
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i ->
        executor.submit(() -> processRequest(i)));
}

// CompletableFuture composition
CompletableFuture<Result> result = fetchUser(id)
    .thenCompose(user -> fetchOrders(user.id()))
    .thenApply(orders -> processOrders(orders))
    .exceptionally(ex -> handleError(ex))
    .orTimeout(5, TimeUnit.SECONDS);

// Thread pool configuration
ThreadPoolExecutor executor = new ThreadPoolExecutor(
    10, 50, 60L, TimeUnit.SECONDS,
    new ArrayBlockingQueue<>(1000),
    new ThreadPoolExecutor.CallerRunsPolicy()
);

// Lock with timeout
ReentrantLock lock = new ReentrantLock();
if (lock.tryLock(1, TimeUnit.SECONDS)) {
    try {
        // critical section
    } finally {
        lock.unlock();
    }
}
java
// Virtual Threads (Java 21+)
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i ->
        executor.submit(() -> processRequest(i)));
}

// CompletableFuture composition
CompletableFuture<Result> result = fetchUser(id)
    .thenCompose(user -> fetchOrders(user.id()))
    .thenApply(orders -> processOrders(orders))
    .exceptionally(ex -> handleError(ex))
    .orTimeout(5, TimeUnit.SECONDS);

// Thread pool configuration
ThreadPoolExecutor executor = new ThreadPoolExecutor(
    10, 50, 60L, TimeUnit.SECONDS,
    new ArrayBlockingQueue<>(1000),
    new ThreadPoolExecutor.CallerRunsPolicy()
);

// Lock with timeout
ReentrantLock lock = new ReentrantLock();
if (lock.tryLock(1, TimeUnit.SECONDS)) {
    try {
        // critical section
    } finally {
        lock.unlock();
    }
}

Thread Pool Sizing

线程池大小设置

WorkloadFormulaExample
CPU-boundcores8 threads
I/O-boundcores * (1 + wait/compute)80 threads
工作负载计算公式示例
CPU密集型核心数8个线程
I/O密集型核心数 * (1 + 等待时间/计算时间)80个线程

Troubleshooting

故障排查

ProblemCauseSolution
DeadlockCircular lockLock ordering, tryLock
Race conditionMissing syncAdd locks/atomics
Thread starvationUnfair schedulingFair locks
问题原因解决方案
死锁循环锁锁排序、tryLock
竞态条件缺少同步机制添加锁/原子操作
线程饥饿不公平调度公平锁

Debug Commands

调试命令

bash
jstack -l <pid> > threaddump.txt
jcmd <pid> Thread.print
bash
jstack -l <pid> > threaddump.txt
jcmd <pid> Thread.print

Usage

使用方法

Skill("java-concurrency")
Skill("java-concurrency")