返回顶部
j

java-optimizationJava性能优化

执行 Java 代码性能优化,包括 JVM 调优、并发编程、内存管理、缓存策略、数据库优化、集合框架优化等。Invoke when user needs to optimize Java code performance.

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 1.0.0
安全检测
已通过
215
下载量
免费
免费
1
收藏
概述
安装方式
版本历史

java-optimization

Java 性能优化技能

高级 Java 性能优化技术,专注于 JVM 应用性能提升、内存管理、并发处理和系统调优。

性能优化策略

1. 缓存策略 (Caching)

使用 Spring Cache 或 Caffeine 实现高效缓存:

java
// ✅ 使用 Caffeine 本地缓存
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.time.Duration;

public class MaterialService {
private final Cache cache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofMinutes(10))
.recordStats()
.build();

public Material getMaterial(String code) {
return cache.get(code, key -> repository.findByCode(code));
}
}

java
// ✅ 使用 Spring Cache + Redis
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class FormulaService {

@Cacheable(value = formulas, key = #id,
condition = #id != null,
unless = #result == null)
public Formula getFormula(Long id) {
return formulaRepository.findById(id).orElse(null);
}
}

何时使用缓存:

  • - 频繁访问的数据库查询结果
  • 计算成本高的数据
  • 不经常变化的配置数据
  • 第三方 API 调用结果

2. 并行处理 (Parallel Processing)

使用 Stream API 和 Fork/Join 框架:

java
import java.util.stream.Collectors;

// ✅ 并行流处理 CPU 密集型任务
public List calculateBatch(List materials) {
return materials.parallelStream()
.map(this::calculateNutrition)
.collect(Collectors.toList());
}

java
// ✅ 使用 CompletableFuture 异步处理
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncCalculator {
private final ExecutorService executor = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()
);

public CompletableFuture calculateAsync(Material material) {
return CompletableFuture.supplyAsync(() -> {
return calculateNutrition(material);
}, executor);
}

// ✅ 批量异步处理
public CompletableFuture> batchCalculate(List materials) {
List> futures = materials.stream()
.map(m -> calculateAsync(m))
.collect(Collectors.toList());

return CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0]))
.thenApply(v -> futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
}
}

最佳实践:

  • - 并行流适合大数据量和 CPU 密集型操作
  • 小数据集使用顺序流(避免线程切换开销)
  • 使用 @Async 进行异步方法调用
  • 合理设置线程池大小

3. 内存优化 (Memory Optimization)

避免不必要的对象创建

java // ❌ 错误 - 循环内创建对象 for (int i = 0; i < items.size(); i++) { StringBuilder sb = new StringBuilder(); sb.append(items.get(i)); }

// ✅ 正确 - 循环外创建
StringBuilder sb = new StringBuilder(items.size() * 10);
for (String item : items) {
sb.append(item);
}

使用基本类型而非包装类

java // ❌ 错误 - 使用包装类 List values = new ArrayList<>(); int sum = 0; for (Integer value : values) { sum += value; // 自动拆箱 }

// ✅ 正确 - 使用基本类型
int[] values = new int[size];
int sum = 0;
for (int value : values) {
sum += value;
}

使用 String.join 替代字符串拼接

java // ❌ 错误 - 低效的字符串拼接 String result = ; for (String item : items) { result += item + ,; }

// ✅ 正确 - 使用 String.join
String result = String.join(,, items);

// ✅ 或使用 StringBuilder
StringBuilder sb = new StringBuilder();
for (String item : items) {
sb.append(item).append(,);
}

集合初始化时指定容量

java // ❌ 错误 - 默认容量可能导致多次扩容 List list = new ArrayList<>(); for (int i = 0; i < 1000; i++) { list.add(String.valueOf(i)); }

// ✅ 正确 - 预分配容量
List list = new ArrayList<>(1000);
for (int i = 0; i < 1000; i++) {
list.add(String.valueOf(i));
}

4. 数据库查询优化

避免 N+1 查询问题

java // ❌ 错误 - N+1 查询 List formulas = formulaRepository.findAll(); for (Formula formula : formulas) { List materials = materialRepository.findByFormulaId(formula.getId()); }

// ✅ 正确 - 使用 JOIN FETCH
@Query(SELECT f FROM Formula f LEFT JOIN FETCH f.materials WHERE f.deleted = 0)
List findAllWithMaterials();

使用批量操作

java // ✅ 批量插入/更新 @Transactional public void batchInsert(List items) { int batchSize = 50; for (int i = 0; i < items.size(); i++) { entityManager.persist(items.get(i));

if (i % batchSize == 0 && i > 0) {
entityManager.flush();
entityManager.clear();
}
}
}

使用投影查询减少数据传输

java // ✅ 只查询需要的字段 @Query(SELECT new com.example.dto.FormulaSummary(f.id, f.name, f.totalCost) + FROM Formula f WHERE f.deleted = 0) List findSummaries();

5. 并发编程优化

使用线程池

java // ✅ 自定义线程池配置 @Configuration public class ThreadPoolConfig {

@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix(async-executor-);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}

使用并发容器

java // ✅ 线程安全的 Map ConcurrentHashMap cache = new ConcurrentHashMap<>();

// ✅ 原子操作
AtomicLong counter = new AtomicLong(0);
counter.incrementAndGet();

// ✅ 读写锁
ReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock().lock();
try {
return cache.get(key);
} finally {
lock.readLock().unlock();
}

6. JVM 调优参数

堆内存配置

bash

生产环境推荐配置

-Xms4g # 初始堆大小 -Xmx4g # 最大堆大小 -XX:NewRatio=2 # 新生代与老年代比例 -XX:SurvivorRatio=8 # Eden 与 Survivor 比例 -XX:+UseG1GC # 使用 G1 垃圾收集器 -XX:MaxGCPauseMillis=200 # 最大 GC 停顿时间 -XX:+ParallelRefProcEnabled

GC 日志配置

bash

GC 日志记录

-Xloggc:/var/log/gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M

7. Stream API 优化

避免在 Stream 中执行副作用操作

java // ❌ 错误 - forEach 有副作用 List result = new ArrayList<>(); list.stream() .forEach(item -> result.add(transform(item)));

// ✅ 正确 - 使用 map 和 collect
List result = list.stream()
.map(this::transform)
.collect(Collectors.toList());

合理使用并行流

java // ❌ 错误 - 小数据集使用并行流 List smallList = Arrays.asList(1, 2, 3, 4, 5); smallList.parallelStream().map(...); // 线程切换开销大于收益

// ✅ 正确 - 大数据集或 CPU 密集型任务
if (list.size() > 10000) {
return list.parallelStream().map(...).collect(...);
}

8. 锁优化

缩小同步范围

java

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 java-optimization-1776113163 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 java-optimization-1776113163 技能

通过命令行安装

skillhub install java-optimization-1776113163

下载

⬇ 下载 java-optimization v1.0.0(免费)

文件大小: 10.46 KB | 发布时间: 2026-4-15 13:07

v1.0.0 最新 2026-4-15 13:07
Initial release of java-optimization skill.

- Provides concise best practices and practical code samples for JVM tuning, concurrency, memory management, caching, database query optimization, and collection usage in Java.
- Covers advanced optimization techniques including Spring Cache, Caffeine, Fork/Join, CompletableFuture, ThreadPool, GC tuning, lock optimizations, and effective use of Java collections.
- Offers scenario-based recommendations (e.g., when to use caching, parallel streams, read-write locks).
- Includes ready-to-use configuration snippets for thread pools, GC logging, and database querying.
- Written in Chinese for easy adoption by Chinese-speaking Java developers.

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部