# Java性能问题
# 问题一:CPU高负载问题
# 问题描述
- 死循环或无限递归
- 频繁的垃圾回收(GC)
- 线程数量过多
- 复杂计算或算法效率低下
# 解决方案
- 代码优化
// 优化算法复杂度
// 优化前:O(n²)的冒泡排序
public void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// 优化后:使用Java内置排序
Arrays.sort(arr); // 使用改进的快速排序,平均时间复杂度O(nlogn)
- 线程池管理
// 创建合理大小的线程池
int processors = Runtime.getRuntime().availableProcessors();
ExecutorService executor = Executors.newFixedThreadPool(processors + 1);
// 提交任务到线程池
executor.submit(() -> {
// 任务执行逻辑
});
- JVM调优
# 设置合理的堆内存大小
-Xms4g -Xmx4g
# 设置新生代大小
-Xmn1g
# 设置GC策略
-XX:+UseG1GC
- 最佳实践
- 使用性能分析工具(如JProfiler)定位热点
- 采用缓存减少重复计算
- 优化数据结构和算法
- 合理配置线程池参数
# 问题二:系统响应延迟
# 问题描述
- 数据库查询性能差
- 网络延迟高
- 同步调用阻塞
- GC停顿频繁
# 解决方案
- 数据库优化
-- 优化前
SELECT * FROM users WHERE name LIKE '%张%'
-- 优化后
SELECT id, name, age FROM users WHERE name LIKE '张%'
AND id > last_id ORDER BY id LIMIT 100
- 异步处理
// 使用CompletableFuture实现异步调用
CompletableFuture<Result> future1 = CompletableFuture
.supplyAsync(() -> service1.call());
CompletableFuture<Result> future2 = CompletableFuture
.supplyAsync(() -> service2.call());
// 合并结果
CompletableFuture.allOf(future1, future2)
.thenAccept(v -> {
Result result1 = future1.get();
Result result2 = future2.get();
// 处理结果
});
- 缓存应用
// 使用多级缓存策略
public User getUserWithMultiCache(Long userId) {
// 先查本地缓存
User user = localCache.get(userId);
if (user != null) {
return user;
}
// 再查Redis
user = redisCache.get(userId);
if (user != null) {
localCache.put(userId, user);
return user;
}
// 最后查数据库
user = userMapper.selectById(userId);
if (user != null) {
redisCache.put(userId, user);
localCache.put(userId, user);
}
return user;
}
- 最佳实践
- 使用连接池管理数据库连接
- 采用异步编程模型
- 合理使用缓存策略
- 优化GC参数配置