前言:
本文模拟一个项目调优的场景,topic如标题所言,异常处理不当导致OOM内存泄漏。
package com.qcby;
import java.util.HashMap;
import java.util.Map;
/**
* @Author YuLing
* @Date 2024-04-29 12:35
* @Description:
* @Version 1.0
*/
public class LogHandler {
// 定义一个静态的HashMap来缓存日志
private static final Map<String, String> logCache = new HashMap<>();
// 模拟日志处理方法
public static void handleLog(String requestId, String threadId, String cityId) {
// 将日志信息缓存到HashMap中
String key = requestId + "+" + threadId;
logCache.put(key, cityId);
// 假设处理阈值为10
if (logCache.size() >= 10) {
try {
// 批量处理日志并持久化
processAndPersistLogs();
} catch (NumberFormatException e) {
// 异常处理:记录异常信息,但未移除缓存中的日志记录
//logCache.clear();
System.err.println("Error processing logs: " + e.getMessage());
}
}
}
// 模拟处理并持久化日志的方法
private static void processAndPersistLogs() throws NumberFormatException {
// 这里模拟处理日志,可能会抛出NumberFormatException
for (Map.Entry<String, String> entry : logCache.entrySet()) {
String cityId = entry.getValue();
if ("".equals(cityId)) { // 模拟cityId为空的情况
throw new NumberFormatException("cityId is empty");
}
// 假设这里是将日志持久化到数据库的代码
}
// 处理成功后移除缓存中的日志记录
logCache.clear();
}
// 模拟生成日志请求
public static void main(String[] args) {
// 循环生成日志请求
for (int i = 0; i < 1500000000; i++) {
String requestId = "request" + i;
String threadId = "thread" + i % 5; // 模拟5个线程
String cityId = i % 2 == 0 ? "" : "123"; // 模拟偶数请求的cityId为空
handleLog(requestId, threadId, cityId);
}
}
}