1. JVM Full GC优化概述

Full GC(完全垃圾回收)是JVM性能调优中的关键指标,频繁的Full GC会导致应用暂停时间过长,影响系统响应性能。本文从架构师的角度深入分析Full GC的优化策略、内存控制机制、垃圾回收器选择以及性能监控方案,为企业级Java应用提供完整的性能优化解决方案。

1.1 Full GC性能影响分析

1
2
3
4
5
6
7
8
9
10
11
12
13
┌─────────────────────────────────────────────────────────┐
│ 应用层 │
│ (响应延迟、吞吐量下降、用户体验影响) │
├─────────────────────────────────────────────────────────┤
│ JVM层 │
│ (Full GC暂停、内存分配失败、OOM异常) │
├─────────────────────────────────────────────────────────┤
│ 系统层 │
│ (CPU使用率、内存使用率、磁盘I/O) │
├─────────────────────────────────────────────────────────┤
│ 硬件层 │
│ (内存容量、CPU性能、存储性能) │
└─────────────────────────────────────────────────────────┘

1.2 Full GC优化目标

  1. 减少Full GC频率: 降低Full GC触发次数
  2. 缩短暂停时间: 减少Full GC暂停时间
  3. 提高吞吐量: 优化整体应用性能
  4. 内存控制: 防止内存泄漏和OOM
  5. 监控告警: 建立完善的GC监控体系

2. 垃圾回收器选择与调优

2.1 智能GC选择器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// 智能GC选择器
@Component
@Slf4j
public class IntelligentGCSelector {

private final ApplicationMetrics applicationMetrics;
private final SystemMetrics systemMetrics;
private final MeterRegistry meterRegistry;

public IntelligentGCSelector(ApplicationMetrics applicationMetrics,
SystemMetrics systemMetrics,
MeterRegistry meterRegistry) {
this.applicationMetrics = applicationMetrics;
this.systemMetrics = systemMetrics;
this.meterRegistry = meterRegistry;
}

// 选择最优GC策略
public GCStrategy selectOptimalGCStrategy(ApplicationProfile profile) {
log.info("Selecting optimal GC strategy for application profile: {}", profile);

try {
// 分析应用特征
ApplicationCharacteristics characteristics = analyzeApplicationCharacteristics(profile);

// 根据特征选择GC策略
GCStrategy strategy = selectGCStrategyByCharacteristics(characteristics);

// 优化GC参数
optimizeGCParameters(strategy, characteristics);

// 记录选择结果
recordGCSelection(strategy);

return strategy;

} catch (Exception e) {
log.error("Error selecting GC strategy", e);
meterRegistry.counter("gc.selection.error").increment();
return getDefaultGCStrategy();
}
}

// 分析应用特征
private ApplicationCharacteristics analyzeApplicationCharacteristics(ApplicationProfile profile) {
ApplicationCharacteristics characteristics = new ApplicationCharacteristics();

// 分析内存使用模式
MemoryUsagePattern memoryPattern = analyzeMemoryUsagePattern(profile);
characteristics.setMemoryUsagePattern(memoryPattern);

// 分析对象生命周期
ObjectLifecyclePattern lifecyclePattern = analyzeObjectLifecyclePattern(profile);
characteristics.setObjectLifecyclePattern(lifecyclePattern);

// 分析并发特征
ConcurrencyPattern concurrencyPattern = analyzeConcurrencyPattern(profile);
characteristics.setConcurrencyPattern(concurrencyPattern);

// 分析延迟要求
LatencyRequirement latencyRequirement = analyzeLatencyRequirement(profile);
characteristics.setLatencyRequirement(latencyRequirement);

return characteristics;
}

// 分析内存使用模式
private MemoryUsagePattern analyzeMemoryUsagePattern(ApplicationProfile profile) {
MemoryUsagePattern pattern = new MemoryUsagePattern();

// 分析堆内存使用
long heapUsage = profile.getMaxHeapSize();
if (heapUsage > 8 * 1024 * 1024 * 1024) { // 8GB
pattern.setHeapSizeCategory(HeapSizeCategory.LARGE);
} else if (heapUsage > 2 * 1024 * 1024 * 1024) { // 2GB
pattern.setHeapSizeCategory(HeapSizeCategory.MEDIUM);
} else {
pattern.setHeapSizeCategory(HeapSizeCategory.SMALL);
}

// 分析内存分配速率
double allocationRate = profile.getAllocationRate();
if (allocationRate > 1000) { // 1000MB/s
pattern.setAllocationRateCategory(AllocationRateCategory.HIGH);
} else if (allocationRate > 100) { // 100MB/s
pattern.setAllocationRateCategory(AllocationRateCategory.MEDIUM);
} else {
pattern.setAllocationRateCategory(AllocationRateCategory.LOW);
}

// 分析内存碎片化程度
double fragmentationRatio = profile.getFragmentationRatio();
if (fragmentationRatio > 0.3) {
pattern.setFragmentationLevel(FragmentationLevel.HIGH);
} else if (fragmentationRatio > 0.1) {
pattern.setFragmentationLevel(FragmentationLevel.MEDIUM);
} else {
pattern.setFragmentationLevel(FragmentationLevel.LOW);
}

return pattern;
}

// 分析对象生命周期
private ObjectLifecyclePattern analyzeObjectLifecyclePattern(ApplicationProfile profile) {
ObjectLifecyclePattern pattern = new ObjectLifecyclePattern();

// 分析短生命周期对象比例
double shortLivedRatio = profile.getShortLivedObjectRatio();
if (shortLivedRatio > 0.8) {
pattern.setShortLivedObjectLevel(ShortLivedObjectLevel.HIGH);
} else if (shortLivedRatio > 0.5) {
pattern.setShortLivedObjectLevel(ShortLivedObjectLevel.MEDIUM);
} else {
pattern.setShortLivedObjectLevel(ShortLivedObjectLevel.LOW);
}

// 分析长生命周期对象比例
double longLivedRatio = profile.getLongLivedObjectRatio();
if (longLivedRatio > 0.5) {
pattern.setLongLivedObjectLevel(LongLivedObjectLevel.HIGH);
} else if (longLivedRatio > 0.2) {
pattern.setLongLivedObjectLevel(LongLivedObjectLevel.MEDIUM);
} else {
pattern.setLongLivedObjectLevel(LongLivedObjectLevel.LOW);
}

return pattern;
}

// 分析并发特征
private ConcurrencyPattern analyzeConcurrencyPattern(ApplicationProfile profile) {
ConcurrencyPattern pattern = new ConcurrencyPattern();

// 分析线程数量
int threadCount = profile.getThreadCount();
if (threadCount > 100) {
pattern.setThreadLevel(ThreadLevel.HIGH);
} else if (threadCount > 20) {
pattern.setThreadLevel(ThreadLevel.MEDIUM);
} else {
pattern.setThreadLevel(ThreadLevel.LOW);
}

// 分析并发度
double concurrencyLevel = profile.getConcurrencyLevel();
if (concurrencyLevel > 0.8) {
pattern.setConcurrencyLevel(ConcurrencyLevel.HIGH);
} else if (concurrencyLevel > 0.5) {
pattern.setConcurrencyLevel(ConcurrencyLevel.MEDIUM);
} else {
pattern.setConcurrencyLevel(ConcurrencyLevel.LOW);
}

return pattern;
}

// 分析延迟要求
private LatencyRequirement analyzeLatencyRequirement(ApplicationProfile profile) {
LatencyRequirement requirement = new LatencyRequirement();

// 分析响应时间要求
double responseTimeRequirement = profile.getResponseTimeRequirement();
if (responseTimeRequirement < 100) { // 100ms
requirement.setResponseTimeLevel(ResponseTimeLevel.STRICT);
} else if (responseTimeRequirement < 500) { // 500ms
requirement.setResponseTimeLevel(ResponseTimeLevel.MODERATE);
} else {
requirement.setResponseTimeLevel(ResponseTimeLevel.RELAXED);
}

// 分析暂停时间容忍度
double pauseTimeTolerance = profile.getPauseTimeTolerance();
if (pauseTimeTolerance < 10) { // 10ms
requirement.setPauseTimeLevel(PauseTimeLevel.STRICT);
} else if (pauseTimeTolerance < 100) { // 100ms
requirement.setPauseTimeLevel(PauseTimeLevel.MODERATE);
} else {
requirement.setPauseTimeLevel(PauseTimeLevel.RELAXED);
}

return requirement;
}

// 根据特征选择GC策略
private GCStrategy selectGCStrategyByCharacteristics(ApplicationCharacteristics characteristics) {
MemoryUsagePattern memoryPattern = characteristics.getMemoryUsagePattern();
ObjectLifecyclePattern lifecyclePattern = characteristics.getObjectLifecyclePattern();
ConcurrencyPattern concurrencyPattern = characteristics.getConcurrencyPattern();
LatencyRequirement latencyRequirement = characteristics.getLatencyRequirement();

// 根据内存大小选择
if (memoryPattern.getHeapSizeCategory() == HeapSizeCategory.LARGE) {
if (latencyRequirement.getPauseTimeLevel() == PauseTimeLevel.STRICT) {
return createG1GCStrategy();
} else {
return createParallelGCStrategy();
}
}

// 根据延迟要求选择
if (latencyRequirement.getPauseTimeLevel() == PauseTimeLevel.STRICT) {
return createG1GCStrategy();
}

// 根据并发特征选择
if (concurrencyPattern.getConcurrencyLevel() == ConcurrencyLevel.HIGH) {
return createCMSGCStrategy();
}

// 默认选择
return createParallelGCStrategy();
}

// 创建G1GC策略
private GCStrategy createG1GCStrategy() {
GCStrategy strategy = new GCStrategy();
strategy.setGcType(GCType.G1GC);
strategy.setMaxGCPauseMillis(10);
strategy.setG1HeapRegionSize(16);
strategy.setG1NewSizePercent(30);
strategy.setG1MaxNewSizePercent(40);
strategy.setG1MixedGCCountTarget(8);
strategy.setG1OldCSetRegionThreshold(10);

log.info("Selected G1GC strategy for low-latency requirements");
return strategy;
}

// 创建ParallelGC策略
private GCStrategy createParallelGCStrategy() {
GCStrategy strategy = new GCStrategy();
strategy.setGcType(GCType.PARALLEL_GC);
strategy.setParallelGCThreads(Runtime.getRuntime().availableProcessors());
strategy.setMaxGCPauseMillis(100);
strategy.setGCTimeRatio(19);

log.info("Selected ParallelGC strategy for high-throughput requirements");
return strategy;
}

// 创建CMS策略
private GCStrategy createCMSGCStrategy() {
GCStrategy strategy = new GCStrategy();
strategy.setGcType(GCType.CMS);
strategy.setCMSInitiatingOccupancyFraction(70);
strategy.setCMSInitiatingOccupancyFractionOnly(true);
strategy.setUseCMSInitiatingOccupancyOnly(true);

log.info("Selected CMS strategy for concurrent requirements");
return strategy;
}

// 优化GC参数
private void optimizeGCParameters(GCStrategy strategy, ApplicationCharacteristics characteristics) {
// 根据应用特征优化参数
MemoryUsagePattern memoryPattern = characteristics.getMemoryUsagePattern();

if (strategy.getGcType() == GCType.G1GC) {
// 优化G1GC参数
optimizeG1GCParameters(strategy, memoryPattern);
} else if (strategy.getGcType() == GCType.PARALLEL_GC) {
// 优化ParallelGC参数
optimizeParallelGCParameters(strategy, memoryPattern);
} else if (strategy.getGcType() == GCType.CMS) {
// 优化CMS参数
optimizeCMSParameters(strategy, memoryPattern);
}
}

// 优化G1GC参数
private void optimizeG1GCParameters(GCStrategy strategy, MemoryUsagePattern memoryPattern) {
if (memoryPattern.getAllocationRateCategory() == AllocationRateCategory.HIGH) {
strategy.setG1NewSizePercent(40);
strategy.setG1MaxNewSizePercent(50);
}

if (memoryPattern.getFragmentationLevel() == FragmentationLevel.HIGH) {
strategy.setG1MixedGCCountTarget(16);
strategy.setG1OldCSetRegionThreshold(5);
}
}

// 优化ParallelGC参数
private void optimizeParallelGCParameters(GCStrategy strategy, MemoryUsagePattern memoryPattern) {
if (memoryPattern.getAllocationRateCategory() == AllocationRateCategory.HIGH) {
strategy.setMaxGCPauseMillis(50);
strategy.setGCTimeRatio(9);
}
}

// 优化CMS参数
private void optimizeCMSParameters(GCStrategy strategy, MemoryUsagePattern memoryPattern) {
if (memoryPattern.getAllocationRateCategory() == AllocationRateCategory.HIGH) {
strategy.setCMSInitiatingOccupancyFraction(60);
}
}

// 记录GC选择
private void recordGCSelection(GCStrategy strategy) {
meterRegistry.counter("gc.selection.success")
.tag("gc_type", strategy.getGcType().name())
.increment();

log.info("GC strategy selected: {}", strategy);
}

// 获取默认GC策略
private GCStrategy getDefaultGCStrategy() {
return createParallelGCStrategy();
}
}

2.2 GC策略配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// GC策略配置
@Data
@Builder
public class GCStrategy {

private GCType gcType;
private int maxGCPauseMillis;
private int parallelGCThreads;
private int gCTimeRatio;
private int g1HeapRegionSize;
private int g1NewSizePercent;
private int g1MaxNewSizePercent;
private int g1MixedGCCountTarget;
private int g1OldCSetRegionThreshold;
private int cMSInitiatingOccupancyFraction;
private boolean cMSInitiatingOccupancyFractionOnly;
private boolean useCMSInitiatingOccupancyOnly;

// GC类型枚举
public enum GCType {
SERIAL_GC("Serial GC"),
PARALLEL_GC("Parallel GC"),
CMS("Concurrent Mark Sweep"),
G1GC("G1 Garbage Collector"),
ZGC("Z Garbage Collector"),
SHENANDOAH("Shenandoah GC");

private final String description;

GCType(String description) {
this.description = description;
}

public String getDescription() {
return description;
}
}
}

3. 内存泄漏检测与修复

3.1 智能内存泄漏检测器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// 智能内存泄漏检测器
@Component
@Slf4j
public class IntelligentMemoryLeakDetector {

private final MemoryAnalyzer memoryAnalyzer;
private final HeapDumpAnalyzer heapDumpAnalyzer;
private final MeterRegistry meterRegistry;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);

public IntelligentMemoryLeakDetector(MemoryAnalyzer memoryAnalyzer,
HeapDumpAnalyzer heapDumpAnalyzer,
MeterRegistry meterRegistry) {
this.memoryAnalyzer = memoryAnalyzer;
this.heapDumpAnalyzer = heapDumpAnalyzer;
this.meterRegistry = meterRegistry;

// 启动内存泄漏检测任务
startMemoryLeakDetection();
}

// 启动内存泄漏检测
private void startMemoryLeakDetection() {
// 定期检测内存使用趋势
scheduler.scheduleAtFixedRate(() -> {
try {
detectMemoryLeakTrends();
} catch (Exception e) {
log.error("Error detecting memory leak trends", e);
}
}, 0, 5, TimeUnit.MINUTES);

// 定期分析堆内存
scheduler.scheduleAtFixedRate(() -> {
try {
analyzeHeapMemory();
} catch (Exception e) {
log.error("Error analyzing heap memory", e);
}
}, 0, 30, TimeUnit.MINUTES);

// 定期生成堆转储
scheduler.scheduleAtFixedRate(() -> {
try {
generateHeapDumpIfNeeded();
} catch (Exception e) {
log.error("Error generating heap dump", e);
}
}, 0, 1, TimeUnit.HOURS);
}

// 检测内存泄漏趋势
public void detectMemoryLeakTrends() {
log.info("Detecting memory leak trends");

try {
// 获取内存使用历史数据
List<MemoryUsageSnapshot> snapshots = memoryAnalyzer.getMemoryUsageHistory(24); // 24小时

if (snapshots.size() < 10) {
log.warn("Insufficient memory usage data for trend analysis");
return;
}

// 分析内存使用趋势
MemoryLeakTrend trend = analyzeMemoryTrend(snapshots);

// 检测潜在的内存泄漏
List<PotentialMemoryLeak> potentialLeaks = detectPotentialLeaks(trend);

// 处理检测到的内存泄漏
processPotentialLeaks(potentialLeaks);

// 更新指标
meterRegistry.gauge("memory_leak.potential_count", potentialLeaks.size()).register();

} catch (Exception e) {
log.error("Error detecting memory leak trends", e);
meterRegistry.counter("memory_leak.detection.error").increment();
}
}

// 分析内存趋势
private MemoryLeakTrend analyzeMemoryTrend(List<MemoryUsageSnapshot> snapshots) {
MemoryLeakTrend trend = new MemoryLeakTrend();

// 计算内存使用增长率
double growthRate = calculateMemoryGrowthRate(snapshots);
trend.setGrowthRate(growthRate);

// 计算内存使用波动性
double volatility = calculateMemoryVolatility(snapshots);
trend.setVolatility(volatility);

// 计算内存使用趋势
TrendDirection direction = calculateTrendDirection(snapshots);
trend.setDirection(direction);

// 计算内存泄漏风险
LeakRiskLevel riskLevel = calculateLeakRiskLevel(growthRate, volatility, direction);
trend.setRiskLevel(riskLevel);

return trend;
}

// 计算内存增长率
private double calculateMemoryGrowthRate(List<MemoryUsageSnapshot> snapshots) {
if (snapshots.size() < 2) {
return 0.0;
}

MemoryUsageSnapshot first = snapshots.get(0);
MemoryUsageSnapshot last = snapshots.get(snapshots.size() - 1);

long timeDiff = last.getTimestamp() - first.getTimestamp();
long memoryDiff = last.getUsedMemory() - first.getUsedMemory();

if (timeDiff == 0) {
return 0.0;
}

// 计算每小时的内存增长率
return (double) memoryDiff / (timeDiff / (1000 * 60 * 60));
}

// 计算内存波动性
private double calculateMemoryVolatility(List<MemoryUsageSnapshot> snapshots) {
if (snapshots.size() < 2) {
return 0.0;
}

// 计算内存使用的标准差
double mean = snapshots.stream()
.mapToLong(MemoryUsageSnapshot::getUsedMemory)
.average()
.orElse(0.0);

double variance = snapshots.stream()
.mapToDouble(snapshot -> Math.pow(snapshot.getUsedMemory() - mean, 2))
.average()
.orElse(0.0);

return Math.sqrt(variance);
}

// 计算趋势方向
private TrendDirection calculateTrendDirection(List<MemoryUsageSnapshot> snapshots) {
if (snapshots.size() < 3) {
return TrendDirection.STABLE;
}

// 使用线性回归分析趋势
double slope = calculateLinearRegressionSlope(snapshots);

if (slope > 0.1) {
return TrendDirection.INCREASING;
} else if (slope < -0.1) {
return TrendDirection.DECREASING;
} else {
return TrendDirection.STABLE;
}
}

// 计算线性回归斜率
private double calculateLinearRegressionSlope(List<MemoryUsageSnapshot> snapshots) {
int n = snapshots.size();
double sumX = 0, sumY = 0, sumXY = 0, sumXX = 0;

for (int i = 0; i < n; i++) {
double x = i;
double y = snapshots.get(i).getUsedMemory();

sumX += x;
sumY += y;
sumXY += x * y;
sumXX += x * x;
}

return (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
}

// 计算内存泄漏风险
private LeakRiskLevel calculateLeakRiskLevel(double growthRate, double volatility, TrendDirection direction) {
if (direction == TrendDirection.INCREASING && growthRate > 100) { // 100MB/hour
return LeakRiskLevel.HIGH;
} else if (direction == TrendDirection.INCREASING && growthRate > 50) { // 50MB/hour
return LeakRiskLevel.MEDIUM;
} else if (volatility > 1000) { // 1GB
return LeakRiskLevel.MEDIUM;
} else {
return LeakRiskLevel.LOW;
}
}

// 检测潜在的内存泄漏
private List<PotentialMemoryLeak> detectPotentialLeaks(MemoryLeakTrend trend) {
List<PotentialMemoryLeak> potentialLeaks = new ArrayList<>();

if (trend.getRiskLevel() == LeakRiskLevel.HIGH) {
// 高风险:立即检测
potentialLeaks.addAll(detectHighRiskLeaks());
} else if (trend.getRiskLevel() == LeakRiskLevel.MEDIUM) {
// 中风险:定期检测
potentialLeaks.addAll(detectMediumRiskLeaks());
}

return potentialLeaks;
}

// 检测高风险泄漏
private List<PotentialMemoryLeak> detectHighRiskLeaks() {
List<PotentialMemoryLeak> leaks = new ArrayList<>();

try {
// 检测大对象
List<LargeObject> largeObjects = detectLargeObjects();
for (LargeObject obj : largeObjects) {
PotentialMemoryLeak leak = PotentialMemoryLeak.builder()
.type(LeakType.LARGE_OBJECT)
.description("Large object detected: " + obj.getClassName())
.size(obj.getSize())
.riskLevel(LeakRiskLevel.HIGH)
.build();
leaks.add(leak);
}

// 检测循环引用
List<CircularReference> circularRefs = detectCircularReferences();
for (CircularReference ref : circularRefs) {
PotentialMemoryLeak leak = PotentialMemoryLeak.builder()
.type(LeakType.CIRCULAR_REFERENCE)
.description("Circular reference detected: " + ref.getDescription())
.riskLevel(LeakRiskLevel.HIGH)
.build();
leaks.add(leak);
}

// 检测未关闭的资源
List<UnclosedResource> unclosedResources = detectUnclosedResources();
for (UnclosedResource resource : unclosedResources) {
PotentialMemoryLeak leak = PotentialMemoryLeak.builder()
.type(LeakType.UNCLOSED_RESOURCE)
.description("Unclosed resource detected: " + resource.getResourceType())
.riskLevel(LeakRiskLevel.HIGH)
.build();
leaks.add(leak);
}

} catch (Exception e) {
log.error("Error detecting high-risk leaks", e);
}

return leaks;
}

// 检测中风险泄漏
private List<PotentialMemoryLeak> detectMediumRiskLeaks() {
List<PotentialMemoryLeak> leaks = new ArrayList<>();

try {
// 检测内存碎片
MemoryFragmentation fragmentation = analyzeMemoryFragmentation();
if (fragmentation.getFragmentationRatio() > 0.3) {
PotentialMemoryLeak leak = PotentialMemoryLeak.builder()
.type(LeakType.MEMORY_FRAGMENTATION)
.description("High memory fragmentation detected")
.riskLevel(LeakRiskLevel.MEDIUM)
.build();
leaks.add(leak);
}

// 检测缓存泄漏
List<CacheLeak> cacheLeaks = detectCacheLeaks();
for (CacheLeak cacheLeak : cacheLeaks) {
PotentialMemoryLeak leak = PotentialMemoryLeak.builder()
.type(LeakType.CACHE_LEAK)
.description("Cache leak detected: " + cacheLeak.getCacheName())
.riskLevel(LeakRiskLevel.MEDIUM)
.build();
leaks.add(leak);
}

} catch (Exception e) {
log.error("Error detecting medium-risk leaks", e);
}

return leaks;
}

// 处理潜在的内存泄漏
private void processPotentialLeaks(List<PotentialMemoryLeak> potentialLeaks) {
for (PotentialMemoryLeak leak : potentialLeaks) {
try {
// 记录泄漏信息
log.warn("Potential memory leak detected: {}", leak);

// 发送告警
sendMemoryLeakAlert(leak);

// 尝试自动修复
attemptAutoFix(leak);

// 更新指标
meterRegistry.counter("memory_leak.detected")
.tag("type", leak.getType().name())
.tag("risk_level", leak.getRiskLevel().name())
.increment();

} catch (Exception e) {
log.error("Error processing potential leak: {}", leak, e);
}
}
}

// 发送内存泄漏告警
private void sendMemoryLeakAlert(PotentialMemoryLeak leak) {
try {
Alert alert = Alert.builder()
.title("Memory Leak Detected")
.description(leak.getDescription())
.severity(leak.getRiskLevel() == LeakRiskLevel.HIGH ?
AlertSeverity.CRITICAL : AlertSeverity.WARNING)
.timestamp(System.currentTimeMillis())
.build();

// 这里可以发送到告警系统
log.info("Memory leak alert sent: {}", alert);

} catch (Exception e) {
log.error("Error sending memory leak alert", e);
}
}

// 尝试自动修复
private void attemptAutoFix(PotentialMemoryLeak leak) {
try {
switch (leak.getType()) {
case LARGE_OBJECT:
// 尝试清理大对象
cleanupLargeObjects();
break;
case CIRCULAR_REFERENCE:
// 尝试打破循环引用
breakCircularReferences();
break;
case UNCLOSED_RESOURCE:
// 尝试关闭未关闭的资源
closeUnclosedResources();
break;
case MEMORY_FRAGMENTATION:
// 尝试整理内存碎片
defragmentMemory();
break;
case CACHE_LEAK:
// 尝试清理缓存泄漏
cleanupCacheLeaks();
break;
}

log.info("Auto-fix attempted for leak type: {}", leak.getType());

} catch (Exception e) {
log.error("Error attempting auto-fix for leak: {}", leak, e);
}
}

// 分析堆内存
private void analyzeHeapMemory() {
log.info("Analyzing heap memory");

try {
// 获取堆内存信息
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();

// 分析堆内存使用情况
HeapAnalysis analysis = analyzeHeapUsage(heapUsage);

// 检测异常情况
detectHeapAnomalies(analysis);

// 更新指标
meterRegistry.gauge("heap.used", heapUsage.getUsed()).register();
meterRegistry.gauge("heap.max", heapUsage.getMax()).register();
meterRegistry.gauge("heap.usage_ratio",
(double) heapUsage.getUsed() / heapUsage.getMax()).register();

} catch (Exception e) {
log.error("Error analyzing heap memory", e);
meterRegistry.counter("heap.analysis.error").increment();
}
}

// 生成堆转储
private void generateHeapDumpIfNeeded() {
try {
// 检查是否需要生成堆转储
if (shouldGenerateHeapDump()) {
String dumpPath = generateHeapDump();
log.info("Heap dump generated: {}", dumpPath);

// 分析堆转储
analyzeHeapDump(dumpPath);

meterRegistry.counter("heap_dump.generated").increment();
}

} catch (Exception e) {
log.error("Error generating heap dump", e);
meterRegistry.counter("heap_dump.error").increment();
}
}

// 检查是否需要生成堆转储
private boolean shouldGenerateHeapDump() {
try {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();

// 如果堆内存使用率超过80%,生成堆转储
double usageRatio = (double) heapUsage.getUsed() / heapUsage.getMax();
return usageRatio > 0.8;

} catch (Exception e) {
log.error("Error checking heap dump requirement", e);
return false;
}
}

// 生成堆转储
private String generateHeapDump() throws IOException {
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
String dumpPath = "/tmp/heap_dump_" + timestamp + ".hprof";

// 使用jmap生成堆转储
ProcessBuilder pb = new ProcessBuilder("jmap", "-dump:format=b,file=" + dumpPath,
String.valueOf(ProcessHandle.current().pid()));
Process process = pb.start();

try {
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("Failed to generate heap dump, exit code: " + exitCode);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while generating heap dump", e);
}

return dumpPath;
}

// 分析堆转储
private void analyzeHeapDump(String dumpPath) {
try {
// 使用堆转储分析器分析
HeapDumpAnalysis analysis = heapDumpAnalyzer.analyze(dumpPath);

// 检测内存泄漏
List<MemoryLeak> leaks = analysis.getMemoryLeaks();
for (MemoryLeak leak : leaks) {
log.warn("Memory leak found in heap dump: {}", leak);
}

// 更新指标
meterRegistry.gauge("heap_dump.leak_count", leaks.size()).register();

} catch (Exception e) {
log.error("Error analyzing heap dump: {}", dumpPath, e);
}
}
}

4. 内存控制与优化

4.1 智能内存控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// 智能内存控制器
@Component
@Slf4j
public class IntelligentMemoryController {

private final MemoryPoolManager memoryPoolManager;
private final ObjectPoolManager objectPoolManager;
private final CacheManager cacheManager;
private final MeterRegistry meterRegistry;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);

public IntelligentMemoryController(MemoryPoolManager memoryPoolManager,
ObjectPoolManager objectPoolManager,
CacheManager cacheManager,
MeterRegistry meterRegistry) {
this.memoryPoolManager = memoryPoolManager;
this.objectPoolManager = objectPoolManager;
this.cacheManager = cacheManager;
this.meterRegistry = meterRegistry;

// 启动内存控制任务
startMemoryControl();
}

// 启动内存控制
private void startMemoryControl() {
// 定期监控内存使用
scheduler.scheduleAtFixedRate(() -> {
try {
monitorMemoryUsage();
} catch (Exception e) {
log.error("Error monitoring memory usage", e);
}
}, 0, 1, TimeUnit.SECONDS);

// 定期优化内存分配
scheduler.scheduleAtFixedRate(() -> {
try {
optimizeMemoryAllocation();
} catch (Exception e) {
log.error("Error optimizing memory allocation", e);
}
}, 0, 30, TimeUnit.SECONDS);

// 定期清理内存
scheduler.scheduleAtFixedRate(() -> {
try {
performMemoryCleanup();
} catch (Exception e) {
log.error("Error performing memory cleanup", e);
}
}, 0, 5, TimeUnit.MINUTES);
}

// 监控内存使用
public void monitorMemoryUsage() {
try {
// 获取内存使用信息
MemoryUsageInfo usageInfo = getMemoryUsageInfo();

// 检查内存使用阈值
checkMemoryThresholds(usageInfo);

// 更新指标
updateMemoryMetrics(usageInfo);

} catch (Exception e) {
log.error("Error monitoring memory usage", e);
meterRegistry.counter("memory.monitoring.error").increment();
}
}

// 获取内存使用信息
private MemoryUsageInfo getMemoryUsageInfo() {
MemoryUsageInfo info = new MemoryUsageInfo();

// 获取堆内存使用
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
info.setHeapUsed(heapUsage.getUsed());
info.setHeapMax(heapUsage.getMax());
info.setHeapCommitted(heapUsage.getCommitted());

// 获取非堆内存使用
MemoryUsage nonHeapUsage = memoryBean.getNonHeapMemoryUsage();
info.setNonHeapUsed(nonHeapUsage.getUsed());
info.setNonHeapMax(nonHeapUsage.getMax());
info.setNonHeapCommitted(nonHeapUsage.getCommitted());

// 获取内存池信息
List<MemoryPoolMXBean> memoryPools = ManagementFactory.getMemoryPoolMXBeans();
Map<String, MemoryPoolUsage> poolUsages = new HashMap<>();

for (MemoryPoolMXBean pool : memoryPools) {
MemoryUsage poolUsage = pool.getUsage();
MemoryPoolUsage poolUsageInfo = MemoryPoolUsage.builder()
.name(pool.getName())
.used(poolUsage.getUsed())
.max(poolUsage.getMax())
.committed(poolUsage.getCommitted())
.build();
poolUsages.put(pool.getName(), poolUsageInfo);
}

info.setPoolUsages(poolUsages);

return info;
}

// 检查内存使用阈值
private void checkMemoryThresholds(MemoryUsageInfo usageInfo) {
// 检查堆内存阈值
double heapUsageRatio = (double) usageInfo.getHeapUsed() / usageInfo.getHeapMax();

if (heapUsageRatio > 0.9) {
// 堆内存使用率超过90%,触发紧急清理
triggerEmergencyCleanup();
} else if (heapUsageRatio > 0.8) {
// 堆内存使用率超过80%,触发常规清理
triggerRegularCleanup();
} else if (heapUsageRatio > 0.7) {
// 堆内存使用率超过70%,触发预防性清理
triggerPreventiveCleanup();
}

// 检查非堆内存阈值
double nonHeapUsageRatio = (double) usageInfo.getNonHeapUsed() / usageInfo.getNonHeapMax();

if (nonHeapUsageRatio > 0.8) {
// 非堆内存使用率过高,触发清理
triggerNonHeapCleanup();
}

// 检查内存池阈值
for (Map.Entry<String, MemoryPoolUsage> entry : usageInfo.getPoolUsages().entrySet()) {
String poolName = entry.getKey();
MemoryPoolUsage poolUsage = entry.getValue();

if (poolUsage.getMax() > 0) {
double poolUsageRatio = (double) poolUsage.getUsed() / poolUsage.getMax();

if (poolUsageRatio > 0.9) {
log.warn("Memory pool {} usage is high: {}%", poolName, poolUsageRatio * 100);
triggerPoolSpecificCleanup(poolName);
}
}
}
}

// 触发紧急清理
private void triggerEmergencyCleanup() {
log.warn("Triggering emergency memory cleanup");

try {
// 强制垃圾回收
System.gc();

// 清理缓存
cacheManager.clearAllCaches();

// 清理对象池
objectPoolManager.clearAllPools();

// 清理内存池
memoryPoolManager.clearAllPools();

meterRegistry.counter("memory.cleanup.emergency").increment();

} catch (Exception e) {
log.error("Error in emergency cleanup", e);
meterRegistry.counter("memory.cleanup.emergency.error").increment();
}
}

// 触发常规清理
private void triggerRegularCleanup() {
log.info("Triggering regular memory cleanup");

try {
// 清理过期缓存
cacheManager.clearExpiredCaches();

// 清理对象池
objectPoolManager.clearExpiredObjects();

// 清理内存池
memoryPoolManager.clearExpiredPools();

meterRegistry.counter("memory.cleanup.regular").increment();

} catch (Exception e) {
log.error("Error in regular cleanup", e);
meterRegistry.counter("memory.cleanup.regular.error").increment();
}
}

// 触发预防性清理
private void triggerPreventiveCleanup() {
log.info("Triggering preventive memory cleanup");

try {
// 清理长期未使用的缓存
cacheManager.clearUnusedCaches();

// 清理长期未使用的对象
objectPoolManager.clearUnusedObjects();

meterRegistry.counter("memory.cleanup.preventive").increment();

} catch (Exception e) {
log.error("Error in preventive cleanup", e);
meterRegistry.counter("memory.cleanup.preventive.error").increment();
}
}

// 触发非堆内存清理
private void triggerNonHeapCleanup() {
log.info("Triggering non-heap memory cleanup");

try {
// 清理元空间
// 这里可以实现元空间清理逻辑

meterRegistry.counter("memory.cleanup.non_heap").increment();

} catch (Exception e) {
log.error("Error in non-heap cleanup", e);
meterRegistry.counter("memory.cleanup.non_heap.error").increment();
}
}

// 触发内存池特定清理
private void triggerPoolSpecificCleanup(String poolName) {
log.info("Triggering pool-specific cleanup for: {}", poolName);

try {
// 根据内存池类型进行特定清理
if (poolName.contains("Eden")) {
// 清理新生代
cleanupYoungGeneration();
} else if (poolName.contains("Old")) {
// 清理老年代
cleanupOldGeneration();
} else if (poolName.contains("Metaspace")) {
// 清理元空间
cleanupMetaspace();
}

meterRegistry.counter("memory.cleanup.pool_specific")
.tag("pool_name", poolName)
.increment();

} catch (Exception e) {
log.error("Error in pool-specific cleanup for: {}", poolName, e);
meterRegistry.counter("memory.cleanup.pool_specific.error")
.tag("pool_name", poolName)
.increment();
}
}

// 优化内存分配
public void optimizeMemoryAllocation() {
log.info("Optimizing memory allocation");

try {
// 分析内存分配模式
MemoryAllocationPattern pattern = analyzeMemoryAllocationPattern();

// 优化内存池配置
optimizeMemoryPoolConfiguration(pattern);

// 优化对象池配置
optimizeObjectPoolConfiguration(pattern);

// 优化缓存配置
optimizeCacheConfiguration(pattern);

meterRegistry.counter("memory.optimization.success").increment();

} catch (Exception e) {
log.error("Error optimizing memory allocation", e);
meterRegistry.counter("memory.optimization.error").increment();
}
}

// 执行内存清理
public void performMemoryCleanup() {
log.info("Performing memory cleanup");

try {
// 清理过期对象
cleanupExpiredObjects();

// 清理未使用的资源
cleanupUnusedResources();

// 整理内存碎片
defragmentMemory();

// 更新指标
meterRegistry.counter("memory.cleanup.performed").increment();

} catch (Exception e) {
log.error("Error performing memory cleanup", e);
meterRegistry.counter("memory.cleanup.error").increment();
}
}

// 更新内存指标
private void updateMemoryMetrics(MemoryUsageInfo usageInfo) {
// 更新堆内存指标
meterRegistry.gauge("memory.heap.used", usageInfo.getHeapUsed()).register();
meterRegistry.gauge("memory.heap.max", usageInfo.getHeapMax()).register();
meterRegistry.gauge("memory.heap.committed", usageInfo.getHeapCommitted()).register();
meterRegistry.gauge("memory.heap.usage_ratio",
(double) usageInfo.getHeapUsed() / usageInfo.getHeapMax()).register();

// 更新非堆内存指标
meterRegistry.gauge("memory.non_heap.used", usageInfo.getNonHeapUsed()).register();
meterRegistry.gauge("memory.non_heap.max", usageInfo.getNonHeapMax()).register();
meterRegistry.gauge("memory.non_heap.committed", usageInfo.getNonHeapCommitted()).register();

// 更新内存池指标
for (Map.Entry<String, MemoryPoolUsage> entry : usageInfo.getPoolUsages().entrySet()) {
String poolName = entry.getKey();
MemoryPoolUsage poolUsage = entry.getValue();

meterRegistry.gauge("memory.pool.used", poolUsage.getUsed())
.tag("pool_name", poolName)
.register();
meterRegistry.gauge("memory.pool.max", poolUsage.getMax())
.tag("pool_name", poolName)
.register();
}
}
}

5. 性能监控与告警

5.1 GC性能监控配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// GC性能监控配置
@Configuration
public class GCPerformanceMonitoringConfig {

@Bean
public AlertRule highFullGCFrequencyAlertRule() {
return AlertRule.builder()
.name("High Full GC Frequency")
.description("Full GC frequency is too high")
.condition("gc.full.frequency > 10 per minute")
.severity(AlertSeverity.WARNING)
.enabled(true)
.build();
}

@Bean
public AlertRule longFullGCPauseAlertRule() {
return AlertRule.builder()
.name("Long Full GC Pause")
.description("Full GC pause time is too long")
.condition("gc.full.pause_time > 1000ms")
.severity(AlertSeverity.CRITICAL)
.enabled(true)
.build();
}

@Bean
public AlertRule highMemoryUsageAlertRule() {
return AlertRule.builder()
.name("High Memory Usage")
.description("Memory usage is too high")
.condition("memory.heap.usage_ratio > 0.9")
.severity(AlertSeverity.CRITICAL)
.enabled(true)
.build();
}

@Bean
public AlertRule memoryLeakAlertRule() {
return AlertRule.builder()
.name("Memory Leak Detected")
.description("Potential memory leak detected")
.condition("memory_leak.potential_count > 0")
.severity(AlertSeverity.WARNING)
.enabled(true)
.build();
}

@Bean
public AlertRule lowGCThroughputAlertRule() {
return AlertRule.builder()
.name("Low GC Throughput")
.description("GC throughput is too low")
.condition("gc.throughput < 0.95")
.severity(AlertSeverity.WARNING)
.enabled(true)
.build();
}
}

5.2 GC指标收集器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// GC指标收集器
@Component
@Slf4j
public class GCMetricsCollector {

private final MeterRegistry meterRegistry;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);

public GCMetricsCollector(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;

// 启动GC指标收集
startGCMetricsCollection();
}

// 启动GC指标收集
private void startGCMetricsCollection() {
// 收集GC指标
scheduler.scheduleAtFixedRate(() -> {
try {
collectGCMetrics();
} catch (Exception e) {
log.error("Error collecting GC metrics", e);
}
}, 0, 5, TimeUnit.SECONDS);

// 收集内存指标
scheduler.scheduleAtFixedRate(() -> {
try {
collectMemoryMetrics();
} catch (Exception e) {
log.error("Error collecting memory metrics", e);
}
}, 0, 1, TimeUnit.SECONDS);
}

// 收集GC指标
private void collectGCMetrics() {
try {
List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();

for (GarbageCollectorMXBean gcBean : gcBeans) {
String gcName = gcBean.getName();

// 收集GC次数
long collectionCount = gcBean.getCollectionCount();
meterRegistry.gauge("gc.collection.count", collectionCount)
.tag("gc_name", gcName)
.register();

// 收集GC时间
long collectionTime = gcBean.getCollectionTime();
meterRegistry.gauge("gc.collection.time", collectionTime)
.tag("gc_name", gcName)
.register();

// 计算GC频率
double gcFrequency = calculateGCFrequency(collectionCount);
meterRegistry.gauge("gc.frequency", gcFrequency)
.tag("gc_name", gcName)
.register();

// 计算GC吞吐量
double gcThroughput = calculateGCThroughput(collectionTime);
meterRegistry.gauge("gc.throughput", gcThroughput)
.tag("gc_name", gcName)
.register();

// 判断是否为Full GC
if (isFullGC(gcName)) {
meterRegistry.gauge("gc.full.count", collectionCount)
.tag("gc_name", gcName)
.register();
meterRegistry.gauge("gc.full.time", collectionTime)
.tag("gc_name", gcName)
.register();
}
}

} catch (Exception e) {
log.error("Error collecting GC metrics", e);
}
}

// 收集内存指标
private void collectMemoryMetrics() {
try {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();

// 堆内存指标
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
meterRegistry.gauge("memory.heap.used", heapUsage.getUsed()).register();
meterRegistry.gauge("memory.heap.max", heapUsage.getMax()).register();
meterRegistry.gauge("memory.heap.committed", heapUsage.getCommitted()).register();

// 非堆内存指标
MemoryUsage nonHeapUsage = memoryBean.getNonHeapMemoryUsage();
meterRegistry.gauge("memory.non_heap.used", nonHeapUsage.getUsed()).register();
meterRegistry.gauge("memory.non_heap.max", nonHeapUsage.getMax()).register();
meterRegistry.gauge("memory.non_heap.committed", nonHeapUsage.getCommitted()).register();

// 内存池指标
List<MemoryPoolMXBean> memoryPools = ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean pool : memoryPools) {
String poolName = pool.getName();
MemoryUsage poolUsage = pool.getUsage();

meterRegistry.gauge("memory.pool.used", poolUsage.getUsed())
.tag("pool_name", poolName)
.register();
meterRegistry.gauge("memory.pool.max", poolUsage.getMax())
.tag("pool_name", poolName)
.register();
}

} catch (Exception e) {
log.error("Error collecting memory metrics", e);
}
}

// 计算GC频率
private double calculateGCFrequency(long collectionCount) {
// 这里可以根据时间窗口计算GC频率
return collectionCount / 60.0; // 每分钟GC次数
}

// 计算GC吞吐量
private double calculateGCThroughput(long collectionTime) {
// GC吞吐量 = (总时间 - GC时间) / 总时间
long totalTime = System.currentTimeMillis();
return Math.max(0, (totalTime - collectionTime) / (double) totalTime);
}

// 判断是否为Full GC
private boolean isFullGC(String gcName) {
return gcName.contains("Full") || gcName.contains("Old") || gcName.contains("Tenured");
}
}

6. 总结

JVM Full GC优化与内存控制是Java应用性能调优的核心内容。本文从架构师的角度深入分析了Full GC的优化策略、内存控制机制、垃圾回收器选择以及性能监控方案,为企业级Java应用提供了完整的性能优化解决方案。

6.1 优化关键点

  1. GC选择: 根据应用特征选择合适的垃圾回收器
  2. 内存控制: 智能内存分配和清理机制
  3. 泄漏检测: 自动检测和修复内存泄漏
  4. 性能监控: 完善的GC和内存监控体系
  5. 告警机制: 及时发现问题并处理

6.2 技术优势

  1. 减少Full GC: 降低Full GC频率和暂停时间
  2. 内存优化: 提高内存使用效率
  3. 自动检测: 自动检测和修复内存问题
  4. 实时监控: 实时监控GC和内存状态
  5. 智能告警: 智能告警和自动处理

6.3 实施要点

  1. GC调优: 根据应用特征调优GC参数
  2. 内存监控: 建立完善的内存监控体系
  3. 泄漏检测: 定期检测和修复内存泄漏
  4. 性能测试: 定期进行性能压力测试
  5. 持续优化: 基于监控数据进行持续优化

6.4 最佳实践

  1. 选择合适的GC: 根据应用特征选择GC算法
  2. 合理设置参数: 根据硬件配置设置GC参数
  3. 监控内存使用: 建立完善的内存监控体系
  4. 及时处理问题: 及时检测和处理内存问题
  5. 定期优化: 定期进行性能优化和调优

通过本文的学习,您应该已经掌握了JVM Full GC优化与内存控制的核心技术,能够设计和实现高性能的Java应用系统,为企业级应用提供可靠的内存管理保障。