执行 Java 代码性能优化,包括 JVM 调优、并发编程、内存管理、缓存策略、数据库优化、集合框架优化等。Invoke when user needs to optimize Java code performance.
高级 Java 性能优化技术,专注于 JVM 应用性能提升、内存管理、并发处理和系统调优。
使用 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
.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);
}
}
何时使用缓存:
使用 Stream API 和 Fork/Join 框架:
java
import java.util.stream.Collectors;
// ✅ 并行流处理 CPU 密集型任务
public List
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
return CompletableFuture.supplyAsync(() -> {
return calculateNutrition(material);
}, executor);
}
// ✅ 批量异步处理
public CompletableFuture> batchCalculate(List
List
.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()));
}
}
最佳实践:
// ✅ 正确 - 循环外创建
StringBuilder sb = new StringBuilder(items.size() * 10);
for (String item : items) {
sb.append(item);
}
// ✅ 正确 - 使用基本类型
int[] values = new int[size];
int sum = 0;
for (int value : values) {
sum += value;
}
// ✅ 正确 - 使用 String.join
String result = String.join(,, items);
// ✅ 或使用 StringBuilder
StringBuilder sb = new StringBuilder();
for (String item : items) {
sb.append(item).append(,);
}
// ✅ 正确 - 预分配容量
List
for (int i = 0; i < 1000; i++) {
list.add(String.valueOf(i));
}
// ✅ 正确 - 使用 JOIN FETCH
@Query(SELECT f FROM Formula f LEFT JOIN FETCH f.materials WHERE f.deleted = 0)
List
if (i % batchSize == 0 && i > 0) {
entityManager.flush();
entityManager.clear();
}
}
}
@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;
}
}
// ✅ 原子操作
AtomicLong counter = new AtomicLong(0);
counter.incrementAndGet();
// ✅ 读写锁
ReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock().lock();
try {
return cache.get(key);
} finally {
lock.readLock().unlock();
}
// ✅ 正确 - 使用 map 和 collect
List
.map(this::transform)
.collect(Collectors.toList());
// ✅ 正确 - 大数据集或 CPU 密集型任务
if (list.size() > 10000) {
return list.parallelStream().map(...).collect(...);
}
该技能支持在以下平台通过对话安装:
帮我安装 SkillHub 和 java-optimization-1776113163 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 java-optimization-1776113163 技能
skillhub install java-optimization-1776113163
文件大小: 10.46 KB | 发布时间: 2026-4-15 13:07