1. Java内存概述

Java内存是Java虚拟机运行时的核心资源,包括堆内存、栈内存、方法区、程序计数器等。本文将详细介绍Java内存模型、内存管理策略、垃圾回收机制、内存优化技术和性能调优的完整解决方案。

1.1 核心功能

  1. 内存模型: 堆内存、栈内存、方法区、程序计数器
  2. 内存管理: 内存分配、内存回收、内存监控
  3. 垃圾回收: GC算法、GC调优、GC监控
  4. 内存优化: 内存泄漏、内存溢出、内存调优
  5. 性能调优: JVM参数、内存配置、性能监控

1.2 技术架构

1
2
3
4
5
Java应用 → JVM内存 → 垃圾回收 → 内存优化 → 性能调优
↓ ↓ ↓ ↓ ↓
对象创建 → 内存分配 → 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
/**
* Java内存配置类
*/
@Configuration
public class JavaMemoryConfig {

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

@Value("${java-memory.stack-size:1m}")
private String stackSize;

/**
* Java内存配置属性
*/
@Bean
public JavaMemoryProperties javaMemoryProperties() {
return JavaMemoryProperties.builder()
.heapSize(heapSize)
.stackSize(stackSize)
.build();
}

/**
* 内存管理器
*/
@Bean
public MemoryManager memoryManager() {
return new MemoryManager(javaMemoryProperties());
}

/**
* 垃圾回收监控器
*/
@Bean
public GarbageCollectionMonitor gcMonitor() {
return new GarbageCollectionMonitor(javaMemoryProperties());
}

/**
* 内存性能监控器
*/
@Bean
public MemoryPerformanceMonitor memoryPerformanceMonitor() {
return new MemoryPerformanceMonitor(javaMemoryProperties());
}
}

/**
* Java内存配置属性
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class JavaMemoryProperties {
private String heapSize;
private String stackSize;

// 堆内存配置
private String youngGenSize = "128m";
private String oldGenSize = "384m";
private String metaspaceSize = "256m";

// GC配置
private String gcAlgorithm = "G1GC";
private int gcThreads = 4;
private boolean enableGCLogging = true;

// 内存监控配置
private boolean enableMemoryMonitoring = true;
private int monitoringInterval = 60; // 秒
private boolean enableMemoryLeakDetection = true;

// 性能调优配置
private boolean enableMemoryOptimization = true;
private int maxDirectMemory = 256; // MB
private boolean enableCompressedOops = true;
}

3. Java内存模型

3.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
/**
* Java内存模型
*/
@Component
public class JavaMemoryModel {

private final JavaMemoryProperties properties;
private final MemoryMXBean memoryMXBean;
private final List<GarbageCollectorMXBean> gcMXBeans;

public JavaMemoryModel(JavaMemoryProperties properties) {
this.properties = properties;
this.memoryMXBean = ManagementFactory.getMemoryMXBean();
this.gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
}

/**
* 获取堆内存信息
* @return 堆内存信息
*/
public MemoryInfo getHeapMemoryInfo() {
MemoryUsage heapUsage = memoryMXBean.getHeapMemoryUsage();

return MemoryInfo.builder()
.init(heapUsage.getInit())
.used(heapUsage.getUsed())
.committed(heapUsage.getCommitted())
.max(heapUsage.getMax())
.build();
}

/**
* 获取非堆内存信息
* @return 非堆内存信息
*/
public MemoryInfo getNonHeapMemoryInfo() {
MemoryUsage nonHeapUsage = memoryMXBean.getNonHeapMemoryUsage();

return MemoryInfo.builder()
.init(nonHeapUsage.getInit())
.used(nonHeapUsage.getUsed())
.committed(nonHeapUsage.getCommitted())
.max(nonHeapUsage.getMax())
.build();
}

/**
* 获取内存池信息
* @return 内存池信息列表
*/
public List<MemoryPoolInfo> getMemoryPoolInfos() {
List<MemoryPoolMXBean> memoryPools = ManagementFactory.getMemoryPoolMXBeans();

return memoryPools.stream()
.map(this::convertToMemoryPoolInfo)
.collect(Collectors.toList());
}

/**
* 转换为内存池信息
* @param memoryPool 内存池MXBean
* @return 内存池信息
*/
private MemoryPoolInfo convertToMemoryPoolInfo(MemoryPoolMXBean memoryPool) {
MemoryUsage usage = memoryPool.getUsage();

return MemoryPoolInfo.builder()
.name(memoryPool.getName())
.type(memoryPool.getType().toString())
.init(usage.getInit())
.used(usage.getUsed())
.committed(usage.getCommitted())
.max(usage.getMax())
.build();
}

/**
* 获取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();
}

/**
* 执行垃圾回收
*/
public void performGC() {
System.gc();
log.info("执行垃圾回收");
}

/**
* 获取内存使用率
* @return 内存使用率
*/
public double getMemoryUsageRatio() {
MemoryInfo heapInfo = getHeapMemoryInfo();
if (heapInfo.getMax() > 0) {
return (double) heapInfo.getUsed() / heapInfo.getMax();
}
return 0.0;
}
}

/**
* 内存信息
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MemoryInfo {
private long init;
private long used;
private long committed;
private long max;
}

/**
* 内存池信息
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MemoryPoolInfo {
private String name;
private String type;
private long init;
private long used;
private long committed;
private long max;
}

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

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
/**
* 内存管理器
*/
@Component
public class MemoryManager {

private final JavaMemoryProperties properties;
private final JavaMemoryModel memoryModel;
private final Map<String, Object> memoryCache = new ConcurrentHashMap<>();

public MemoryManager(JavaMemoryProperties properties) {
this.properties = properties;
this.memoryModel = null; // 注入
}

/**
* 分配内存
* @param size 内存大小(字节)
* @return 内存地址
*/
public long allocateMemory(long size) {
try {
// 检查可用内存
if (!checkAvailableMemory(size)) {
throw new OutOfMemoryError("可用内存不足");
}

// 分配内存
long address = allocateNativeMemory(size);

log.info("分配内存成功: size={}, address={}", size, address);

return address;

} catch (Exception e) {
log.error("分配内存失败: size={}", size, e);
throw new RuntimeException("分配内存失败", e);
}
}

/**
* 释放内存
* @param address 内存地址
* @return 是否成功
*/
public boolean freeMemory(long address) {
try {
// 释放内存
freeNativeMemory(address);

log.info("释放内存成功: address={}", address);

return true;

} catch (Exception e) {
log.error("释放内存失败: address={}", address, e);
return false;
}
}

/**
* 检查可用内存
* @param requiredSize 需要的内存大小
* @return 是否有足够内存
*/
private boolean checkAvailableMemory(long requiredSize) {
MemoryInfo heapInfo = memoryModel.getHeapMemoryInfo();
long availableMemory = heapInfo.getMax() - heapInfo.getUsed();

return availableMemory >= requiredSize;
}

/**
* 分配本地内存
* @param size 内存大小
* @return 内存地址
*/
private long allocateNativeMemory(long size) {
// 使用Unsafe分配本地内存
// 这里只是示例,实际实现需要使用Unsafe
return System.currentTimeMillis();
}

/**
* 释放本地内存
* @param address 内存地址
*/
private void freeNativeMemory(long address) {
// 使用Unsafe释放本地内存
// 这里只是示例,实际实现需要使用Unsafe
log.debug("释放本地内存: address={}", address);
}

/**
* 内存缓存管理
* @param key 缓存键
* @param value 缓存值
* @param ttl 生存时间(秒)
*/
public void putToCache(String key, Object value, int ttl) {
try {
// 检查缓存大小
if (memoryCache.size() >= 10000) {
cleanExpiredCache();
}

// 添加缓存
CacheEntry entry = CacheEntry.builder()
.value(value)
.expireTime(System.currentTimeMillis() + ttl * 1000)
.build();

memoryCache.put(key, entry);

} catch (Exception e) {
log.error("添加缓存失败: key={}", key, e);
}
}

/**
* 从缓存获取
* @param key 缓存键
* @return 缓存值
*/
public Object getFromCache(String key) {
try {
CacheEntry entry = (CacheEntry) memoryCache.get(key);
if (entry != null) {
if (System.currentTimeMillis() < entry.getExpireTime()) {
return entry.getValue();
} else {
memoryCache.remove(key);
}
}
return null;

} catch (Exception e) {
log.error("获取缓存失败: key={}", key, e);
return null;
}
}

/**
* 清理过期缓存
*/
private void cleanExpiredCache() {
try {
long currentTime = System.currentTimeMillis();
Iterator<Map.Entry<String, Object>> iterator = memoryCache.entrySet().iterator();

while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
CacheEntry cacheEntry = (CacheEntry) entry.getValue();

if (currentTime >= cacheEntry.getExpireTime()) {
iterator.remove();
}
}

log.info("清理过期缓存完成: remaining={}", memoryCache.size());

} catch (Exception e) {
log.error("清理过期缓存失败", e);
}
}

/**
* 内存泄漏检测
* @return 内存泄漏信息
*/
public MemoryLeakInfo detectMemoryLeak() {
try {
MemoryInfo heapInfo = memoryModel.getHeapMemoryInfo();
double usageRatio = memoryModel.getMemoryUsageRatio();

MemoryLeakInfo leakInfo = MemoryLeakInfo.builder()
.heapUsage(heapInfo.getUsed())
.heapMax(heapInfo.getMax())
.usageRatio(usageRatio)
.isLeak(usageRatio > 0.8)
.build();

if (leakInfo.isLeak()) {
log.warn("检测到内存泄漏: usageRatio={}", usageRatio);
}

return leakInfo;

} catch (Exception e) {
log.error("内存泄漏检测失败", e);
return MemoryLeakInfo.builder().isLeak(false).build();
}
}
}

/**
* 缓存条目
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CacheEntry {
private Object value;
private long expireTime;
}

/**
* 内存泄漏信息
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MemoryLeakInfo {
private long heapUsage;
private long heapMax;
private double usageRatio;
private boolean isLeak;
}

5. 垃圾回收监控

5.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
/**
* 垃圾回收监控器
*/
@Component
public class GarbageCollectionMonitor {

private final JavaMemoryProperties properties;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final Map<String, GCStats> gcStatsMap = new ConcurrentHashMap<>();

public GarbageCollectionMonitor(JavaMemoryProperties properties) {
this.properties = properties;
if (properties.isEnableMemoryMonitoring()) {
startGCMonitoring();
}
}

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

/**
* 监控GC
*/
private void monitorGC() {
try {
List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();

for (GarbageCollectorMXBean gcMXBean : gcMXBeans) {
String gcName = gcMXBean.getName();
long collectionCount = gcMXBean.getCollectionCount();
long collectionTime = gcMXBean.getCollectionTime();

GCStats stats = gcStatsMap.computeIfAbsent(gcName, k -> new GCStats());

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

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

stats.setLastCollectionCount(collectionCount);
stats.setLastCollectionTime(collectionTime);
stats.setTotalCollectionCount(collectionCount);
stats.setTotalCollectionTime(collectionTime);

// 记录GC日志
if (properties.isEnableGCLogging()) {
log.info("GC监控: name={}, count={}, time={}ms", gcName, collectionCount, collectionTime);
}
}

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

/**
* 获取GC统计信息
* @return GC统计信息
*/
public Map<String, GCStats> getGCStats() {
return new HashMap<>(gcStatsMap);
}

/**
* 获取GC性能指标
* @return GC性能指标
*/
public GCPerformanceMetrics getGCPerformanceMetrics() {
try {
long totalCollectionCount = 0;
long totalCollectionTime = 0;

for (GCStats stats : gcStatsMap.values()) {
totalCollectionCount += stats.getTotalCollectionCount();
totalCollectionTime += stats.getTotalCollectionTime();
}

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

return GCPerformanceMetrics.builder()
.totalCollectionCount(totalCollectionCount)
.totalCollectionTime(totalCollectionTime)
.avgCollectionTime(avgCollectionTime)
.gcStatsMap(new HashMap<>(gcStatsMap))
.build();

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

/**
* 触发GC
*/
public void triggerGC() {
try {
System.gc();
log.info("触发垃圾回收");
} catch (Exception e) {
log.error("触发垃圾回收失败", e);
}
}

/**
* 获取GC建议
* @return GC建议
*/
public List<String> getGCRecommendations() {
List<String> recommendations = new ArrayList<>();

try {
GCPerformanceMetrics metrics = getGCPerformanceMetrics();

// 检查GC频率
if (metrics.getTotalCollectionCount() > 1000) {
recommendations.add("GC频率过高,建议增加堆内存大小");
}

// 检查GC时间
if (metrics.getAvgCollectionTime() > 100) {
recommendations.add("GC时间过长,建议优化GC算法或增加GC线程数");
}

// 检查内存使用率
MemoryInfo heapInfo = new JavaMemoryModel(properties).getHeapMemoryInfo();
double usageRatio = (double) heapInfo.getUsed() / heapInfo.getMax();
if (usageRatio > 0.8) {
recommendations.add("内存使用率过高,建议增加堆内存或优化内存使用");
}

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

return recommendations;
}
}

/**
* 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 GCPerformanceMetrics {
private long totalCollectionCount;
private long totalCollectionTime;
private double avgCollectionTime;
private Map<String, GCStats> gcStatsMap;
}

6. 内存性能监控

6.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
/**
* 内存性能监控器
*/
@Component
public class MemoryPerformanceMonitor {

private final JavaMemoryProperties properties;
private final JavaMemoryModel memoryModel;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final List<MemorySnapshot> memorySnapshots = new ArrayList<>();

public MemoryPerformanceMonitor(JavaMemoryProperties properties) {
this.properties = properties;
this.memoryModel = null; // 注入
if (properties.isEnableMemoryMonitoring()) {
startMemoryMonitoring();
}
}

/**
* 开始内存监控
*/
private void startMemoryMonitoring() {
scheduler.scheduleAtFixedRate(
this::takeMemorySnapshot,
0,
properties.getMonitoringInterval(),
TimeUnit.SECONDS
);
}

/**
* 获取内存快照
*/
private void takeMemorySnapshot() {
try {
MemoryInfo heapInfo = memoryModel.getHeapMemoryInfo();
MemoryInfo nonHeapInfo = memoryModel.getNonHeapMemoryInfo();

MemorySnapshot snapshot = MemorySnapshot.builder()
.timestamp(System.currentTimeMillis())
.heapUsed(heapInfo.getUsed())
.heapMax(heapInfo.getMax())
.nonHeapUsed(nonHeapInfo.getUsed())
.nonHeapMax(nonHeapInfo.getMax())
.build();

memorySnapshots.add(snapshot);

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

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

/**
* 获取内存趋势
* @return 内存趋势
*/
public MemoryTrend getMemoryTrend() {
try {
if (memorySnapshots.size() < 2) {
return MemoryTrend.builder().build();
}

MemorySnapshot latest = memorySnapshots.get(memorySnapshots.size() - 1);
MemorySnapshot previous = memorySnapshots.get(memorySnapshots.size() - 2);

long heapTrend = latest.getHeapUsed() - previous.getHeapUsed();
long nonHeapTrend = latest.getNonHeapUsed() - previous.getNonHeapUsed();

return MemoryTrend.builder()
.heapTrend(heapTrend)
.nonHeapTrend(nonHeapTrend)
.trendDirection(heapTrend > 0 ? "上升" : "下降")
.build();

} catch (Exception e) {
log.error("获取内存趋势失败", e);
return MemoryTrend.builder().build();
}
}

/**
* 获取内存峰值
* @return 内存峰值
*/
public MemoryPeak getMemoryPeak() {
try {
long maxHeapUsed = 0;
long maxNonHeapUsed = 0;
long peakTimestamp = 0;

for (MemorySnapshot snapshot : memorySnapshots) {
if (snapshot.getHeapUsed() > maxHeapUsed) {
maxHeapUsed = snapshot.getHeapUsed();
maxNonHeapUsed = snapshot.getNonHeapUsed();
peakTimestamp = snapshot.getTimestamp();
}
}

return MemoryPeak.builder()
.maxHeapUsed(maxHeapUsed)
.maxNonHeapUsed(maxNonHeapUsed)
.peakTimestamp(peakTimestamp)
.build();

} catch (Exception e) {
log.error("获取内存峰值失败", e);
return MemoryPeak.builder().build();
}
}

/**
* 获取内存使用报告
* @return 内存使用报告
*/
public MemoryUsageReport getMemoryUsageReport() {
try {
MemoryInfo heapInfo = memoryModel.getHeapMemoryInfo();
MemoryInfo nonHeapInfo = memoryModel.getNonHeapMemoryInfo();
MemoryTrend trend = getMemoryTrend();
MemoryPeak peak = getMemoryPeak();

return MemoryUsageReport.builder()
.currentHeapUsed(heapInfo.getUsed())
.currentHeapMax(heapInfo.getMax())
.currentNonHeapUsed(nonHeapInfo.getUsed())
.currentNonHeapMax(nonHeapInfo.getMax())
.heapUsageRatio((double) heapInfo.getUsed() / heapInfo.getMax())
.nonHeapUsageRatio((double) nonHeapInfo.getUsed() / nonHeapInfo.getMax())
.memoryTrend(trend)
.memoryPeak(peak)
.snapshotCount(memorySnapshots.size())
.build();

} catch (Exception e) {
log.error("获取内存使用报告失败", e);
return MemoryUsageReport.builder().build();
}
}
}

/**
* 内存快照
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MemorySnapshot {
private long timestamp;
private long heapUsed;
private long heapMax;
private long nonHeapUsed;
private long nonHeapMax;
}

/**
* 内存趋势
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MemoryTrend {
private long heapTrend;
private long nonHeapTrend;
private String trendDirection;
}

/**
* 内存峰值
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MemoryPeak {
private long maxHeapUsed;
private long maxNonHeapUsed;
private long peakTimestamp;
}

/**
* 内存使用报告
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MemoryUsageReport {
private long currentHeapUsed;
private long currentHeapMax;
private long currentNonHeapUsed;
private long currentNonHeapMax;
private double heapUsageRatio;
private double nonHeapUsageRatio;
private MemoryTrend memoryTrend;
private MemoryPeak memoryPeak;
private int snapshotCount;
}

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-memory")
public class JavaMemoryController {

@Autowired
private JavaMemoryModel memoryModel;

@Autowired
private MemoryManager memoryManager;

@Autowired
private GarbageCollectionMonitor gcMonitor;

@Autowired
private MemoryPerformanceMonitor performanceMonitor;

/**
* 获取内存信息
*/
@GetMapping("/info")
public ResponseEntity<Map<String, Object>> getMemoryInfo() {
try {
MemoryInfo heapInfo = memoryModel.getHeapMemoryInfo();
MemoryInfo nonHeapInfo = memoryModel.getNonHeapMemoryInfo();
List<MemoryPoolInfo> memoryPools = memoryModel.getMemoryPoolInfos();

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("heapMemory", heapInfo);
response.put("nonHeapMemory", nonHeapInfo);
response.put("memoryPools", memoryPools);

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("/gc")
public ResponseEntity<Map<String, Object>> getGCInfo() {
try {
List<GCInfo> gcInfos = memoryModel.getGCInfos();
Map<String, GCStats> gcStats = gcMonitor.getGCStats();
GCPerformanceMetrics metrics = gcMonitor.getGCPerformanceMetrics();

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

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("/gc/trigger")
public ResponseEntity<Map<String, Object>> triggerGC() {
try {
memoryModel.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);
}
}

/**
* 获取内存使用报告
*/
@GetMapping("/report")
public ResponseEntity<Map<String, Object>> getMemoryReport() {
try {
MemoryUsageReport report = performanceMonitor.getMemoryUsageReport();
MemoryLeakInfo leakInfo = memoryManager.detectMemoryLeak();
List<String> gcRecommendations = gcMonitor.getGCRecommendations();

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

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);
}
}

/**
* 内存缓存操作
*/
@PostMapping("/cache")
public ResponseEntity<Map<String, Object>> cacheOperation(@RequestBody CacheRequest request) {
try {
if ("put".equals(request.getOperation())) {
memoryManager.putToCache(request.getKey(), request.getValue(), request.getTtl());
} else if ("get".equals(request.getOperation())) {
Object value = memoryManager.getFromCache(request.getKey());
Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("value", value);
return ResponseEntity.ok(response);
}

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);
}
}
}

/**
* 缓存请求模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CacheRequest {
private String operation; // put, get
private String key;
private Object value;
private int ttl; // 秒
}

8. 总结

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

8.1 核心优势

  1. 内存模型: 堆内存、栈内存、方法区、程序计数器
  2. 内存管理: 内存分配、内存回收、内存监控
  3. 垃圾回收: GC算法、GC调优、GC监控
  4. 内存优化: 内存泄漏、内存溢出、内存调优
  5. 性能调优: JVM参数、内存配置、性能监控

8.2 最佳实践

  1. 内存管理: 合理的内存分配、及时的内存回收
  2. 垃圾回收: 选择合适的GC算法、优化GC参数
  3. 内存优化: 避免内存泄漏、优化内存使用
  4. 性能监控: 实时监控内存使用、及时发现问题
  5. 调优策略: JVM参数调优、内存配置优化

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