1. Java垃圾回收概述

Java垃圾回收是Java虚拟机自动内存管理的核心机制,通过垃圾回收算法自动回收不再使用的对象,释放内存空间。本文将详细介绍垃圾回收算法、GC调优策略、GC监控机制、性能优化技术和最佳实践的完整解决方案。

1.1 核心功能

  1. 垃圾回收算法: 标记清除、标记复制、标记整理、分代回收
  2. GC调优: GC参数调优、GC策略选择、性能优化
  3. GC监控: GC日志分析、GC性能监控、GC统计
  4. 性能优化: GC停顿优化、吞吐量优化、内存优化
  5. 最佳实践: GC配置、GC监控、GC调优策略

1.2 技术架构

1
2
3
4
5
Java应用 → 对象创建 → 垃圾回收 → GC调优 → 性能优化
↓ ↓ ↓ ↓ ↓
内存分配 → 对象标记 → GC算法 → GC监控 → 系统优化
↓ ↓ ↓ ↓ ↓
堆内存 → 垃圾识别 → GC执行 → GC分析 → 性能提升

2. Java垃圾回收配置

2.1 Maven依赖配置

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
<!-- pom.xml -->
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<!-- Micrometer -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

<!-- JVM监控 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>6.4.0</version>
</dependency>

<!-- Apache Commons Lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>

2.2 Java垃圾回收配置类

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
/**
* Java垃圾回收配置类
*/
@Configuration
public class JavaGCConfig {

@Value("${java-gc.algorithm:G1GC}")
private String gcAlgorithm;

@Value("${java-gc.heap-size:512m}")
private String heapSize;

/**
* Java垃圾回收配置属性
*/
@Bean
public JavaGCProperties javaGCProperties() {
return JavaGCProperties.builder()
.gcAlgorithm(gcAlgorithm)
.heapSize(heapSize)
.build();
}

/**
* GC管理器
*/
@Bean
public GCManager gcManager() {
return new GCManager(javaGCProperties());
}

/**
* GC监控器
*/
@Bean
public GCMonitor gcMonitor() {
return new GCMonitor(javaGCProperties());
}

/**
* GC性能分析器
*/
@Bean
public GCPerformanceAnalyzer gcPerformanceAnalyzer() {
return new GCPerformanceAnalyzer(javaGCProperties());
}
}

/**
* Java垃圾回收配置属性
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class JavaGCProperties {
private String gcAlgorithm;
private String heapSize;

// GC算法配置
private String youngGenGC = "ParNew";
private String oldGenGC = "CMS";
private int gcThreads = 4;
private boolean enableConcurrentGC = true;

// GC调优配置
private int maxGCPauseMillis = 200;
private double gcTimeRatio = 0.1;
private int heapRegionSize = 16; // MB
private boolean enableGCAdaptiveSizePolicy = true;

// GC监控配置
private boolean enableGCLogging = true;
private boolean enableGCVerboseLogging = false;
private String gcLogFile = "gc.log";
private int gcLogRotationCount = 5;

// GC性能配置
private boolean enableGCPerformanceMonitoring = true;
private int monitoringInterval = 60; // 秒
private boolean enableGCStatistics = true;
}

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
/**
* 垃圾回收算法服务
*/
@Service
public class GCAlgorithmService {

private final JavaGCProperties properties;
private final Map<String, GCAlgorithm> algorithms = new HashMap<>();

public GCAlgorithmService(JavaGCProperties properties) {
this.properties = properties;
initializeAlgorithms();
}

/**
* 初始化GC算法
*/
private void initializeAlgorithms() {
algorithms.put("SerialGC", new SerialGCAlgorithm());
algorithms.put("ParallelGC", new ParallelGCAlgorithm());
algorithms.put("CMS", new CMSAlgorithm());
algorithms.put("G1GC", new G1GCAlgorithm());
algorithms.put("ZGC", new ZGCAlgorithm());
algorithms.put("Shenandoah", new ShenandoahAlgorithm());
}

/**
* 获取GC算法
* @param algorithmName 算法名称
* @return GC算法
*/
public GCAlgorithm getGCAlgorithm(String algorithmName) {
return algorithms.get(algorithmName);
}

/**
* 获取所有GC算法
* @return GC算法列表
*/
public List<GCAlgorithm> getAllGCAlgorithms() {
return new ArrayList<>(algorithms.values());
}

/**
* 分析GC算法性能
* @param algorithmName 算法名称
* @return GC性能分析
*/
public GCPerformanceAnalysis analyzeGCPerformance(String algorithmName) {
GCAlgorithm algorithm = algorithms.get(algorithmName);
if (algorithm == null) {
throw new IllegalArgumentException("不支持的GC算法: " + algorithmName);
}

return algorithm.analyzePerformance();
}

/**
* 获取GC算法建议
* @param applicationType 应用类型
* @return GC算法建议
*/
public List<GCAlgorithmRecommendation> getGCAlgorithmRecommendations(String applicationType) {
List<GCAlgorithmRecommendation> recommendations = new ArrayList<>();

switch (applicationType.toLowerCase()) {
case "web":
recommendations.add(new GCAlgorithmRecommendation("G1GC", "适合Web应用,低延迟"));
recommendations.add(new GCAlgorithmRecommendation("ParallelGC", "高吞吐量"));
break;
case "batch":
recommendations.add(new GCAlgorithmRecommendation("ParallelGC", "适合批处理应用,高吞吐量"));
break;
case "realtime":
recommendations.add(new GCAlgorithmRecommendation("ZGC", "适合实时应用,极低延迟"));
recommendations.add(new GCAlgorithmRecommendation("Shenandoah", "低延迟,适合大堆"));
break;
default:
recommendations.add(new GCAlgorithmRecommendation("G1GC", "通用推荐"));
break;
}

return recommendations;
}
}

/**
* GC算法接口
*/
public interface GCAlgorithm {
String getName();
String getDescription();
GCPerformanceAnalysis analyzePerformance();
List<String> getAdvantages();
List<String> getDisadvantages();
String getRecommendedUseCase();
}

/**
* Serial GC算法
*/
public class SerialGCAlgorithm implements GCAlgorithm {

@Override
public String getName() {
return "SerialGC";
}

@Override
public String getDescription() {
return "串行垃圾回收器,单线程执行GC,适合小堆内存和单核CPU";
}

@Override
public GCPerformanceAnalysis analyzePerformance() {
return GCPerformanceAnalysis.builder()
.algorithmName(getName())
.throughput(0.8)
.pauseTime(0.6)
.memoryEfficiency(0.7)
.cpuUsage(0.5)
.build();
}

@Override
public List<String> getAdvantages() {
return Arrays.asList("简单稳定", "内存占用少", "适合小堆");
}

@Override
public List<String> getDisadvantages() {
return Arrays.asList("单线程执行", "停顿时间长", "不适合大堆");
}

@Override
public String getRecommendedUseCase() {
return "适合小堆内存(<100MB)和单核CPU环境";
}
}

/**
* Parallel GC算法
*/
public class ParallelGCAlgorithm implements GCAlgorithm {

@Override
public String getName() {
return "ParallelGC";
}

@Override
public String getDescription() {
return "并行垃圾回收器,多线程执行GC,适合高吞吐量应用";
}

@Override
public GCPerformanceAnalysis analyzePerformance() {
return GCPerformanceAnalysis.builder()
.algorithmName(getName())
.throughput(0.9)
.pauseTime(0.4)
.memoryEfficiency(0.8)
.cpuUsage(0.8)
.build();
}

@Override
public List<String> getAdvantages() {
return Arrays.asList("高吞吐量", "多线程并行", "适合大堆");
}

@Override
public List<String> getDisadvantages() {
return Arrays.asList("停顿时间较长", "CPU使用率高", "不适合低延迟应用");
}

@Override
public String getRecommendedUseCase() {
return "适合批处理应用和高吞吐量要求";
}
}

/**
* G1 GC算法
*/
public class G1GCAlgorithm implements GCAlgorithm {

@Override
public String getName() {
return "G1GC";
}

@Override
public String getDescription() {
return "G1垃圾回收器,低延迟,适合大堆内存应用";
}

@Override
public GCPerformanceAnalysis analyzePerformance() {
return GCPerformanceAnalysis.builder()
.algorithmName(getName())
.throughput(0.7)
.pauseTime(0.9)
.memoryEfficiency(0.8)
.cpuUsage(0.7)
.build();
}

@Override
public List<String> getAdvantages() {
return Arrays.asList("低延迟", "可预测停顿时间", "适合大堆", "并发执行");
}

@Override
public List<String> getDisadvantages() {
return Arrays.asList("吞吐量较低", "内存占用较大", "配置复杂");
}

@Override
public String getRecommendedUseCase() {
return "适合Web应用和低延迟要求";
}
}

/**
* GC性能分析
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GCPerformanceAnalysis {
private String algorithmName;
private double throughput; // 吞吐量 (0-1)
private double pauseTime; // 停顿时间 (0-1)
private double memoryEfficiency; // 内存效率 (0-1)
private double cpuUsage; // CPU使用率 (0-1)
}

/**
* GC算法建议
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GCAlgorithmRecommendation {
private String algorithmName;
private String reason;
}

4. GC管理器

4.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
/**
* GC管理器
*/
@Component
public class GCManager {

private final JavaGCProperties properties;
private final GCAlgorithmService algorithmService;
private final List<GarbageCollectorMXBean> gcMXBeans;

public GCManager(JavaGCProperties properties) {
this.properties = properties;
this.algorithmService = null; // 注入
this.gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
}

/**
* 执行垃圾回收
*/
public void performGC() {
try {
System.gc();
log.info("执行垃圾回收");
} catch (Exception e) {
log.error("执行垃圾回收失败", e);
}
}

/**
* 获取GC信息
* @return GC信息列表
*/
public List<GCInfo> getGCInfos() {
return gcMXBeans.stream()
.map(this::convertToGCInfo)
.collect(Collectors.toList());
}

/**
* 转换为GC信息
* @param gcMXBean GC MXBean
* @return GC信息
*/
private GCInfo convertToGCInfo(GarbageCollectorMXBean gcMXBean) {
return GCInfo.builder()
.name(gcMXBean.getName())
.collectionCount(gcMXBean.getCollectionCount())
.collectionTime(gcMXBean.getCollectionTime())
.build();
}

/**
* 获取GC统计信息
* @return GC统计信息
*/
public GCStatistics getGCStatistics() {
try {
long totalCollectionCount = 0;
long totalCollectionTime = 0;

for (GarbageCollectorMXBean gcMXBean : gcMXBeans) {
totalCollectionCount += gcMXBean.getCollectionCount();
totalCollectionTime += gcMXBean.getCollectionTime();
}

double avgCollectionTime = totalCollectionCount > 0 ?
(double) totalCollectionTime / totalCollectionCount : 0;

return GCStatistics.builder()
.totalCollectionCount(totalCollectionCount)
.totalCollectionTime(totalCollectionTime)
.avgCollectionTime(avgCollectionTime)
.gcInfos(getGCInfos())
.build();

} catch (Exception e) {
log.error("获取GC统计信息失败", e);
return GCStatistics.builder().build();
}
}

/**
* 分析GC性能
* @return GC性能分析
*/
public GCPerformanceAnalysis analyzeGCPerformance() {
try {
GCStatistics stats = getGCStatistics();
String currentAlgorithm = getCurrentGCAlgorithm();

GCAlgorithm algorithm = algorithmService.getGCAlgorithm(currentAlgorithm);
if (algorithm != null) {
return algorithm.analyzePerformance();
}

return GCPerformanceAnalysis.builder()
.algorithmName(currentAlgorithm)
.throughput(0.5)
.pauseTime(0.5)
.memoryEfficiency(0.5)
.cpuUsage(0.5)
.build();

} catch (Exception e) {
log.error("分析GC性能失败", e);
return GCPerformanceAnalysis.builder().build();
}
}

/**
* 获取当前GC算法
* @return GC算法名称
*/
private String getCurrentGCAlgorithm() {
try {
// 通过系统属性获取GC算法
String gcAlgorithm = System.getProperty("java.vm.name");
if (gcAlgorithm.contains("G1")) {
return "G1GC";
} else if (gcAlgorithm.contains("Parallel")) {
return "ParallelGC";
} else if (gcAlgorithm.contains("CMS")) {
return "CMS";
} else if (gcAlgorithm.contains("Serial")) {
return "SerialGC";
} else if (gcAlgorithm.contains("ZGC")) {
return "ZGC";
} else if (gcAlgorithm.contains("Shenandoah")) {
return "Shenandoah";
}

return "Unknown";

} catch (Exception e) {
log.error("获取当前GC算法失败", e);
return "Unknown";
}
}

/**
* 获取GC调优建议
* @return GC调优建议
*/
public List<GCTuningRecommendation> getGCTuningRecommendations() {
List<GCTuningRecommendation> recommendations = new ArrayList<>();

try {
GCStatistics stats = getGCStatistics();
String currentAlgorithm = getCurrentGCAlgorithm();

// 基于GC统计信息提供调优建议
if (stats.getAvgCollectionTime() > 100) {
recommendations.add(new GCTuningRecommendation(
"减少GC停顿时间",
"增加堆内存大小或调整GC参数",
"HIGH"
));
}

if (stats.getTotalCollectionCount() > 1000) {
recommendations.add(new GCTuningRecommendation(
"减少GC频率",
"增加堆内存大小或优化对象创建",
"MEDIUM"
));
}

// 基于GC算法提供调优建议
switch (currentAlgorithm) {
case "G1GC":
recommendations.add(new GCTuningRecommendation(
"G1GC调优",
"设置-XX:MaxGCPauseMillis=200",
"LOW"
));
break;
case "ParallelGC":
recommendations.add(new GCTuningRecommendation(
"ParallelGC调优",
"设置-XX:ParallelGCThreads=4",
"LOW"
));
break;
}

} catch (Exception e) {
log.error("获取GC调优建议失败", e);
}

return recommendations;
}
}

/**
* GC信息
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GCInfo {
private String name;
private long collectionCount;
private long collectionTime;
}

/**
* GC统计信息
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GCStatistics {
private long totalCollectionCount;
private long totalCollectionTime;
private double avgCollectionTime;
private List<GCInfo> gcInfos;
}

/**
* GC调优建议
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GCTuningRecommendation {
private String title;
private String description;
private String priority; // HIGH, MEDIUM, LOW
}

5. GC监控器

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
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
/**
* GC监控器
*/
@Component
public class GCMonitor {

private final JavaGCProperties properties;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final List<GCMonitorSnapshot> snapshots = new ArrayList<>();
private final Map<String, GCStats> gcStatsMap = new ConcurrentHashMap<>();

public GCMonitor(JavaGCProperties properties) {
this.properties = properties;
if (properties.isEnableGCPerformanceMonitoring()) {
startGCMonitoring();
}
}

/**
* 开始GC监控
*/
private void startGCMonitoring() {
scheduler.scheduleAtFixedRate(
this::takeGCSnapshot,
0,
properties.getMonitoringInterval(),
TimeUnit.SECONDS
);
}

/**
* 获取GC快照
*/
private void takeGCSnapshot() {
try {
List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

MemoryUsage heapUsage = memoryMXBean.getHeapMemoryUsage();
MemoryUsage nonHeapUsage = memoryMXBean.getNonHeapMemoryUsage();

List<GCInfo> gcInfos = gcMXBeans.stream()
.map(gcMXBean -> GCInfo.builder()
.name(gcMXBean.getName())
.collectionCount(gcMXBean.getCollectionCount())
.collectionTime(gcMXBean.getCollectionTime())
.build())
.collect(Collectors.toList());

GCMonitorSnapshot snapshot = GCMonitorSnapshot.builder()
.timestamp(System.currentTimeMillis())
.heapUsed(heapUsage.getUsed())
.heapMax(heapUsage.getMax())
.nonHeapUsed(nonHeapUsage.getUsed())
.nonHeapMax(nonHeapUsage.getMax())
.gcInfos(gcInfos)
.build();

snapshots.add(snapshot);

// 保持最近100个快照
if (snapshots.size() > 100) {
snapshots.remove(0);
}

// 更新GC统计信息
updateGCStats(gcInfos);

} catch (Exception e) {
log.error("获取GC快照失败", e);
}
}

/**
* 更新GC统计信息
* @param gcInfos GC信息列表
*/
private void updateGCStats(List<GCInfo> gcInfos) {
for (GCInfo gcInfo : gcInfos) {
String gcName = gcInfo.getName();
GCStats stats = gcStatsMap.computeIfAbsent(gcName, k -> new GCStats());

// 计算GC频率和时间
if (stats.getLastCollectionCount() > 0) {
long countDiff = gcInfo.getCollectionCount() - stats.getLastCollectionCount();
long timeDiff = gcInfo.getCollectionTime() - stats.getLastCollectionTime();

stats.setCollectionRate(countDiff);
stats.setCollectionTimeRate(timeDiff);
}

stats.setLastCollectionCount(gcInfo.getCollectionCount());
stats.setLastCollectionTime(gcInfo.getCollectionTime());
stats.setTotalCollectionCount(gcInfo.getCollectionCount());
stats.setTotalCollectionTime(gcInfo.getCollectionTime());
}
}

/**
* 获取GC监控报告
* @return GC监控报告
*/
public GCMonitorReport getGCMonitorReport() {
try {
if (snapshots.isEmpty()) {
return GCMonitorReport.builder().build();
}

GCMonitorSnapshot latest = snapshots.get(snapshots.size() - 1);
GCMonitorSnapshot previous = snapshots.size() > 1 ?
snapshots.get(snapshots.size() - 2) : latest;

// 计算GC趋势
long gcCountTrend = latest.getGcInfos().stream()
.mapToLong(GCInfo::getCollectionCount)
.sum() - previous.getGcInfos().stream()
.mapToLong(GCInfo::getCollectionCount)
.sum();

long gcTimeTrend = latest.getGcInfos().stream()
.mapToLong(GCInfo::getCollectionTime)
.sum() - previous.getGcInfos().stream()
.mapToLong(GCInfo::getCollectionTime)
.sum();

// 计算内存趋势
long heapTrend = latest.getHeapUsed() - previous.getHeapUsed();
long nonHeapTrend = latest.getNonHeapUsed() - previous.getNonHeapUsed();

return GCMonitorReport.builder()
.currentSnapshot(latest)
.gcCountTrend(gcCountTrend)
.gcTimeTrend(gcTimeTrend)
.heapTrend(heapTrend)
.nonHeapTrend(nonHeapTrend)
.snapshotCount(snapshots.size())
.gcStatsMap(new HashMap<>(gcStatsMap))
.build();

} catch (Exception e) {
log.error("获取GC监控报告失败", e);
return GCMonitorReport.builder().build();
}
}

/**
* 获取GC告警
* @return GC告警列表
*/
public List<GCAlert> getGCAlerts() {
List<GCAlert> alerts = new ArrayList<>();

try {
GCMonitorReport report = getGCMonitorReport();

// 检查GC频率告警
if (report.getGcCountTrend() > 10) {
alerts.add(new GCAlert(
"GC频率过高",
"GC频率超过阈值",
"HIGH"
));
}

// 检查GC时间告警
if (report.getGcTimeTrend() > 1000) {
alerts.add(new GCAlert(
"GC时间过长",
"GC时间超过阈值",
"HIGH"
));
}

// 检查内存使用率告警
GCMonitorSnapshot latest = report.getCurrentSnapshot();
if (latest != null) {
double heapUsageRatio = (double) latest.getHeapUsed() / latest.getHeapMax();
if (heapUsageRatio > 0.8) {
alerts.add(new GCAlert(
"堆内存使用率过高",
"堆内存使用率超过80%",
"MEDIUM"
));
}
}

} catch (Exception e) {
log.error("获取GC告警失败", e);
}

return alerts;
}
}

/**
* GC监控快照
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GCMonitorSnapshot {
private long timestamp;
private long heapUsed;
private long heapMax;
private long nonHeapUsed;
private long nonHeapMax;
private List<GCInfo> gcInfos;
}

/**
* GC统计信息
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GCStats {
private long lastCollectionCount;
private long lastCollectionTime;
private long totalCollectionCount;
private long totalCollectionTime;
private long collectionRate;
private long collectionTimeRate;
}

/**
* GC监控报告
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GCMonitorReport {
private GCMonitorSnapshot currentSnapshot;
private long gcCountTrend;
private long gcTimeTrend;
private long heapTrend;
private long nonHeapTrend;
private int snapshotCount;
private Map<String, GCStats> gcStatsMap;
}

/**
* GC告警
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GCAlert {
private String title;
private String description;
private String severity; // HIGH, MEDIUM, LOW
}

6. GC性能分析器

6.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
/**
* GC性能分析器
*/
@Component
public class GCPerformanceAnalyzer {

private final JavaGCProperties properties;
private final GCMonitor gcMonitor;

public GCPerformanceAnalyzer(JavaGCProperties properties) {
this.properties = properties;
this.gcMonitor = null; // 注入
}

/**
* 分析GC性能
* @return GC性能分析报告
*/
public GCPerformanceAnalysisReport analyzeGCPerformance() {
try {
GCMonitorReport monitorReport = gcMonitor.getGCMonitorReport();
List<GCAlert> alerts = gcMonitor.getGCAlerts();

// 计算GC性能指标
GCPerformanceMetrics metrics = calculateGCPerformanceMetrics(monitorReport);

// 生成GC优化建议
List<GCOptimizationRecommendation> recommendations = generateGCOptimizationRecommendations(metrics, alerts);

return GCPerformanceAnalysisReport.builder()
.metrics(metrics)
.alerts(alerts)
.recommendations(recommendations)
.analysisTime(System.currentTimeMillis())
.build();

} catch (Exception e) {
log.error("分析GC性能失败", e);
return GCPerformanceAnalysisReport.builder().build();
}
}

/**
* 计算GC性能指标
* @param monitorReport GC监控报告
* @return GC性能指标
*/
private GCPerformanceMetrics calculateGCPerformanceMetrics(GCMonitorReport monitorReport) {
try {
GCMonitorSnapshot snapshot = monitorReport.getCurrentSnapshot();
if (snapshot == null) {
return GCPerformanceMetrics.builder().build();
}

// 计算内存使用率
double heapUsageRatio = (double) snapshot.getHeapUsed() / snapshot.getHeapMax();
double nonHeapUsageRatio = (double) snapshot.getNonHeapUsed() / snapshot.getNonHeapMax();

// 计算GC效率
double gcEfficiency = calculateGCEfficiency(snapshot.getGcInfos());

// 计算GC频率
double gcFrequency = calculateGCFrequency(monitorReport.getGcStatsMap());

return GCPerformanceMetrics.builder()
.heapUsageRatio(heapUsageRatio)
.nonHeapUsageRatio(nonHeapUsageRatio)
.gcEfficiency(gcEfficiency)
.gcFrequency(gcFrequency)
.gcCountTrend(monitorReport.getGcCountTrend())
.gcTimeTrend(monitorReport.getGcTimeTrend())
.build();

} catch (Exception e) {
log.error("计算GC性能指标失败", e);
return GCPerformanceMetrics.builder().build();
}
}

/**
* 计算GC效率
* @param gcInfos GC信息列表
* @return GC效率
*/
private double calculateGCEfficiency(List<GCInfo> gcInfos) {
try {
if (gcInfos.isEmpty()) {
return 0.0;
}

long totalCollectionTime = gcInfos.stream()
.mapToLong(GCInfo::getCollectionTime)
.sum();

long totalCollectionCount = gcInfos.stream()
.mapToLong(GCInfo::getCollectionCount)
.sum();

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

double avgCollectionTime = (double) totalCollectionTime / totalCollectionCount;

// GC效率 = 1 / 平均GC时间(毫秒)
return Math.min(1.0, 1000.0 / avgCollectionTime);

} catch (Exception e) {
log.error("计算GC效率失败", e);
return 0.0;
}
}

/**
* 计算GC频率
* @param gcStatsMap GC统计信息
* @return GC频率
*/
private double calculateGCFrequency(Map<String, GCStats> gcStatsMap) {
try {
if (gcStatsMap.isEmpty()) {
return 0.0;
}

long totalCollectionRate = gcStatsMap.values().stream()
.mapToLong(GCStats::getCollectionRate)
.sum();

// GC频率 = GC次数 / 监控间隔(秒)
return (double) totalCollectionRate / properties.getMonitoringInterval();

} catch (Exception e) {
log.error("计算GC频率失败", e);
return 0.0;
}
}

/**
* 生成GC优化建议
* @param metrics GC性能指标
* @param alerts GC告警
* @return GC优化建议
*/
private List<GCOptimizationRecommendation> generateGCOptimizationRecommendations(
GCPerformanceMetrics metrics, List<GCAlert> alerts) {
List<GCOptimizationRecommendation> recommendations = new ArrayList<>();

try {
// 基于内存使用率提供建议
if (metrics.getHeapUsageRatio() > 0.8) {
recommendations.add(new GCOptimizationRecommendation(
"增加堆内存大小",
"当前堆内存使用率过高,建议增加-Xmx参数",
"HIGH"
));
}

// 基于GC效率提供建议
if (metrics.getGcEfficiency() < 0.5) {
recommendations.add(new GCOptimizationRecommendation(
"优化GC算法",
"当前GC效率较低,建议考虑更换GC算法",
"MEDIUM"
));
}

// 基于GC频率提供建议
if (metrics.getGcFrequency() > 1.0) {
recommendations.add(new GCOptimizationRecommendation(
"减少GC频率",
"当前GC频率过高,建议优化对象创建和内存使用",
"MEDIUM"
));
}

// 基于告警提供建议
for (GCAlert alert : alerts) {
if ("HIGH".equals(alert.getSeverity())) {
recommendations.add(new GCOptimizationRecommendation(
"处理" + alert.getTitle(),
alert.getDescription(),
"HIGH"
));
}
}

} catch (Exception e) {
log.error("生成GC优化建议失败", e);
}

return recommendations;
}
}

/**
* GC性能指标
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GCPerformanceMetrics {
private double heapUsageRatio;
private double nonHeapUsageRatio;
private double gcEfficiency;
private double gcFrequency;
private long gcCountTrend;
private long gcTimeTrend;
}

/**
* GC优化建议
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GCOptimizationRecommendation {
private String title;
private String description;
private String priority; // HIGH, MEDIUM, LOW
}

/**
* GC性能分析报告
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GCPerformanceAnalysisReport {
private GCPerformanceMetrics metrics;
private List<GCAlert> alerts;
private List<GCOptimizationRecommendation> recommendations;
private long analysisTime;
}

7. Java垃圾回收控制器

7.1 Java垃圾回收控制器

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
/**
* Java垃圾回收控制器
*/
@RestController
@RequestMapping("/api/v1/java-gc")
public class JavaGCController {

@Autowired
private GCManager gcManager;

@Autowired
private GCAlgorithmService algorithmService;

@Autowired
private GCMonitor gcMonitor;

@Autowired
private GCPerformanceAnalyzer performanceAnalyzer;

/**
* 获取GC信息
*/
@GetMapping("/info")
public ResponseEntity<Map<String, Object>> getGCInfo() {
try {
List<GCInfo> gcInfos = gcManager.getGCInfos();
GCStatistics statistics = gcManager.getGCStatistics();

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("gcInfos", gcInfos);
response.put("statistics", statistics);

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("获取GC信息失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "获取GC信息失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 获取GC算法信息
*/
@GetMapping("/algorithms")
public ResponseEntity<Map<String, Object>> getGCAlgorithms() {
try {
List<GCAlgorithm> algorithms = algorithmService.getAllGCAlgorithms();

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("algorithms", algorithms);

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("获取GC算法信息失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "获取GC算法信息失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 触发垃圾回收
*/
@PostMapping("/trigger")
public ResponseEntity<Map<String, Object>> triggerGC() {
try {
gcManager.performGC();

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("message", "垃圾回收已触发");

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("触发垃圾回收失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "触发垃圾回收失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 获取GC监控报告
*/
@GetMapping("/monitor")
public ResponseEntity<Map<String, Object>> getGCMonitorReport() {
try {
GCMonitorReport report = gcMonitor.getGCMonitorReport();
List<GCAlert> alerts = gcMonitor.getGCAlerts();

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("report", report);
response.put("alerts", alerts);

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("获取GC监控报告失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "获取GC监控报告失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 获取GC性能分析报告
*/
@GetMapping("/performance")
public ResponseEntity<Map<String, Object>> getGCPerformanceReport() {
try {
GCPerformanceAnalysisReport report = performanceAnalyzer.analyzeGCPerformance();

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("report", report);

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("获取GC性能分析报告失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "获取GC性能分析报告失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 获取GC调优建议
*/
@GetMapping("/recommendations")
public ResponseEntity<Map<String, Object>> getGCRecommendations(@RequestParam String applicationType) {
try {
List<GCAlgorithmRecommendation> algorithmRecommendations =
algorithmService.getGCAlgorithmRecommendations(applicationType);
List<GCTuningRecommendation> tuningRecommendations =
gcManager.getGCTuningRecommendations();

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("algorithmRecommendations", algorithmRecommendations);
response.put("tuningRecommendations", tuningRecommendations);

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("获取GC建议失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "获取GC建议失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}
}

8. 总结

通过Java垃圾回收的实现,我们成功构建了一个完整的GC管理框架。关键特性包括:

8.1 核心优势

  1. 垃圾回收算法: 标记清除、标记复制、标记整理、分代回收
  2. GC调优: GC参数调优、GC策略选择、性能优化
  3. GC监控: GC日志分析、GC性能监控、GC统计
  4. 性能优化: GC停顿优化、吞吐量优化、内存优化
  5. 最佳实践: GC配置、GC监控、GC调优策略

8.2 最佳实践

  1. GC算法选择: 根据应用特点选择合适的GC算法
  2. GC参数调优: 合理设置GC参数,平衡吞吐量和延迟
  3. GC监控: 实时监控GC性能,及时发现问题
  4. 性能优化: 优化对象创建,减少GC压力
  5. 调优策略: 基于监控数据进行GC调优

这套Java垃圾回收方案不仅能够提供完整的GC管理能力,还包含了GC算法分析、性能监控、调优建议等核心功能,是企业级Java应用的重要技术基础。