# Java Concurrency

> Thread management, Executor framework, CompletableFuture, synchronization, and virtual threads.

- **Type:** Skill
- **Install:** `agentstack add skill-ngxtm-devkit-java-concurrency`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [ngxtm](https://agentstack.voostack.com/s/ngxtm)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [ngxtm](https://github.com/ngxtm)
- **Source:** https://github.com/ngxtm/devkit/tree/main/rules/java/java-concurrency

## Install

```sh
agentstack add skill-ngxtm-devkit-java-concurrency
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Java Concurrency Standards

## Executor Framework

```java
// Fixed thread pool - bounded, predictable
ExecutorService executor = Executors.newFixedThreadPool(
    Runtime.getRuntime().availableProcessors()
);

// Cached thread pool - unbounded, use carefully
ExecutorService cached = Executors.newCachedThreadPool();

// Scheduled executor
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);

// Virtual threads (Java 21+)
ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor();

// Custom thread pool
ThreadPoolExecutor custom = new ThreadPoolExecutor(
    4,                      // core pool size
    8,                      // max pool size
    60, TimeUnit.SECONDS,   // keep alive
    new LinkedBlockingQueue<>(100),  // work queue
    new ThreadPoolExecutor.CallerRunsPolicy()  // rejection handler
);

// Always shutdown executors
try {
    executor.shutdown();
    if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
        executor.shutdownNow();
    }
} catch (InterruptedException e) {
    executor.shutdownNow();
    Thread.currentThread().interrupt();
}
```

## CompletableFuture

```java
// Async execution
CompletableFuture userFuture = CompletableFuture
    .supplyAsync(() -> userService.findById(id), executor);

// Chaining
CompletableFuture result = userFuture
    .thenApply(User::getEmail)
    .thenApply(String::toLowerCase)
    .exceptionally(ex -> "unknown@example.com");

// Combine multiple futures
CompletableFuture profile = CompletableFuture
    .allOf(userFuture, ordersFuture, preferencesFuture)
    .thenApply(v -> new UserProfile(
        userFuture.join(),
        ordersFuture.join(),
        preferencesFuture.join()
    ));

// Either/race
CompletableFuture fastest = CompletableFuture
    .anyOf(primaryService, fallbackService)
    .thenApply(result -> (String) result);

// Timeout (Java 9+)
CompletableFuture withTimeout = userFuture
    .orTimeout(5, TimeUnit.SECONDS)
    .exceptionally(ex -> defaultUser);
```

## Synchronization

```java
// synchronized block - prefer over method
private final Object lock = new Object();

public void update(String value) {
    synchronized (lock) {
        // critical section
    }
}

// ReentrantLock - more flexible
private final ReentrantLock lock = new ReentrantLock();

public void process() {
    lock.lock();
    try {
        // critical section
    } finally {
        lock.unlock();
    }
}

// ReadWriteLock - multiple readers, single writer
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();

public String read() {
    rwLock.readLock().lock();
    try {
        return data;
    } finally {
        rwLock.readLock().unlock();
    }
}

public void write(String value) {
    rwLock.writeLock().lock();
    try {
        data = value;
    } finally {
        rwLock.writeLock().unlock();
    }
}
```

## Atomic Classes

```java
// Atomic primitives
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
counter.compareAndSet(expected, newValue);

// Atomic reference
AtomicReference configRef = new AtomicReference<>(initialConfig);
configRef.updateAndGet(config -> config.withNewValue(value));

// LongAdder for high contention
LongAdder adder = new LongAdder();
adder.increment();
long sum = adder.sum();
```

## Virtual Threads (Java 21+)

```java
// Simple virtual thread
Thread.startVirtualThread(() -> {
    // blocking I/O is fine
    String data = httpClient.get(url);
    process(data);
});

// With executor
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    List> futures = tasks.stream()
        .map(task -> executor.submit(task::execute))
        .toList();

    for (Future future : futures) {
        results.add(future.get());
    }
}

// Don't use with CPU-bound tasks
// Don't use synchronized for long operations (use ReentrantLock)
```

## Best Practices

1. **Prefer high-level constructs** (Executor, CompletableFuture) over raw threads
2. **Size thread pools** based on task type (CPU-bound: cores, I/O-bound: higher)
3. **Always handle InterruptedException** - restore interrupt status
4. **Use virtual threads** for I/O-bound tasks (Java 21+)
5. **Prefer Atomic classes** over synchronized for simple counters
6. **Immutability** is the best synchronization

## References

- [Executor Patterns](references/executor-patterns.md) - Thread pool configuration, shutdown
- [CompletableFuture](references/completable-future.md) - Async composition patterns
- [Virtual Threads](references/virtual-threads.md) - Java 21+ patterns

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [ngxtm](https://github.com/ngxtm)
- **Source:** [ngxtm/devkit](https://github.com/ngxtm/devkit)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** yes
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-ngxtm-devkit-java-concurrency
- Seller: https://agentstack.voostack.com/s/ngxtm
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
