第238集SpringBoot ThreadLocal架构实战:线程隔离、上下文传递、内存泄漏防护的企业级解决方案

前言

在多线程并发环境中,线程间的数据隔离和上下文传递是构建高并发应用的核心挑战。ThreadLocal作为Java提供的重要并发工具,能够为每个线程提供独立的变量副本,实现线程隔离和上下文传递。然而,ThreadLocal的使用不当会导致内存泄漏、性能问题等严重后果。基于SpringBoot的ThreadLocal架构,不仅能够安全高效地管理线程本地变量,还能实现上下文传递、内存泄漏防护和性能优化。随着微服务架构和高并发系统的普及,构建可扩展、可维护的ThreadLocal框架,已成为企业级架构师必须掌握的核心技能。

本文将深入探讨SpringBoot中ThreadLocal的架构设计与实战应用,从线程隔离到上下文传递,从内存泄漏防护到性能优化,为企业构建稳定、高效的ThreadLocal解决方案提供全面的技术指导。

一、SpringBoot ThreadLocal架构概述与核心原理

1.1 ThreadLocal架构设计

SpringBoot ThreadLocal系统采用分层架构设计,通过线程隔离、上下文传递、内存管理等技术,实现高效的线程本地变量管理能力。

1.2 核心组件架构

二、企业级ThreadLocal管理器设计

2.1 ThreadLocal核心管理器

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
/**
* 企业级ThreadLocal管理器
* 提供线程安全的ThreadLocal管理和内存泄漏防护
*/
@Component
@Slf4j
public class ThreadLocalManager {

private final Map<String, ThreadLocal<?>> threadLocalMap = new ConcurrentHashMap<>();
private final MemoryManager memoryManager;
private final PerformanceMonitor performanceMonitor;
private final LeakDetector leakDetector;
private final ContextManager contextManager;

/**
* 创建ThreadLocal实例
*/
public <T> ThreadLocal<T> createThreadLocal(String name, Class<T> type) {
try {
// 检查是否已存在
if (threadLocalMap.containsKey(name)) {
throw new ThreadLocalException("ThreadLocal已存在: " + name);
}

// 创建ThreadLocal实例
ThreadLocal<T> threadLocal = new ThreadLocal<T>() {
@Override
protected T initialValue() {
try {
return type.newInstance();
} catch (Exception e) {
log.error("ThreadLocal初始值创建失败: {}", name, e);
return null;
}
}

@Override
public void set(T value) {
super.set(value);
// 记录设置操作
memoryManager.recordSet(name, value);
performanceMonitor.recordOperation(name, "set");
}

@Override
public T get() {
T value = super.get();
// 记录获取操作
performanceMonitor.recordOperation(name, "get");
return value;
}

@Override
public void remove() {
T value = get();
super.remove();
// 记录移除操作
memoryManager.recordRemove(name, value);
performanceMonitor.recordOperation(name, "remove");
}
};

// 注册ThreadLocal
threadLocalMap.put(name, threadLocal);

// 注册到内存管理器
memoryManager.registerThreadLocal(name, threadLocal);

log.info("ThreadLocal创建成功: {}", name);
return threadLocal;

} catch (Exception e) {
log.error("ThreadLocal创建失败: {}", name, e);
throw new ThreadLocalException("ThreadLocal创建失败: " + e.getMessage());
}
}

/**
* 获取ThreadLocal实例
*/
@SuppressWarnings("unchecked")
public <T> ThreadLocal<T> getThreadLocal(String name) {
ThreadLocal<?> threadLocal = threadLocalMap.get(name);
if (threadLocal == null) {
throw new ThreadLocalException("ThreadLocal不存在: " + name);
}
return (ThreadLocal<T>) threadLocal;
}

/**
* 设置ThreadLocal值
*/
public <T> void setValue(String name, T value) {
try {
ThreadLocal<T> threadLocal = getThreadLocal(name);
threadLocal.set(value);

// 记录上下文信息
contextManager.recordContext(name, value);

log.debug("ThreadLocal值设置成功: {} = {}", name, value);

} catch (Exception e) {
log.error("ThreadLocal值设置失败: {}", name, e);
throw new ThreadLocalException("ThreadLocal值设置失败: " + e.getMessage());
}
}

/**
* 获取ThreadLocal值
*/
public <T> T getValue(String name) {
try {
ThreadLocal<T> threadLocal = getThreadLocal(name);
T value = threadLocal.get();

// 记录上下文信息
contextManager.recordContext(name, value);

return value;

} catch (Exception e) {
log.error("ThreadLocal值获取失败: {}", name, e);
throw new ThreadLocalException("ThreadLocal值获取失败: " + e.getMessage());
}
}

/**
* 移除ThreadLocal值
*/
public <T> void removeValue(String name) {
try {
ThreadLocal<T> threadLocal = getThreadLocal(name);
threadLocal.remove();

// 清理上下文信息
contextManager.clearContext(name);

log.debug("ThreadLocal值移除成功: {}", name);

} catch (Exception e) {
log.error("ThreadLocal值移除失败: {}", name, e);
throw new ThreadLocalException("ThreadLocal值移除失败: " + e.getMessage());
}
}

/**
* 清理所有ThreadLocal
*/
public void clearAll() {
try {
for (Map.Entry<String, ThreadLocal<?>> entry : threadLocalMap.entrySet()) {
String name = entry.getKey();
ThreadLocal<?> threadLocal = entry.getValue();

try {
threadLocal.remove();
log.debug("ThreadLocal清理成功: {}", name);
} catch (Exception e) {
log.error("ThreadLocal清理失败: {}", name, e);
}
}

// 清理上下文信息
contextManager.clearAllContext();

log.info("所有ThreadLocal清理完成");

} catch (Exception e) {
log.error("ThreadLocal清理失败", e);
throw new ThreadLocalException("ThreadLocal清理失败: " + e.getMessage());
}
}

/**
* 获取ThreadLocal统计信息
*/
public ThreadLocalStatistics getStatistics() {
try {
Map<String, ThreadLocalInfo> threadLocalInfos = new HashMap<>();

for (Map.Entry<String, ThreadLocal<?>> entry : threadLocalMap.entrySet()) {
String name = entry.getKey();
ThreadLocal<?> threadLocal = entry.getValue();

ThreadLocalInfo info = ThreadLocalInfo.builder()
.name(name)
.type(threadLocal.getClass().getSimpleName())
.hasValue(threadLocal.get() != null)
.build();

threadLocalInfos.put(name, info);
}

return ThreadLocalStatistics.builder()
.totalCount(threadLocalMap.size())
.threadLocalInfos(threadLocalInfos)
.memoryUsage(memoryManager.getMemoryUsage())
.performanceMetrics(performanceMonitor.getMetrics())
.leakDetection(leakDetector.getLeakDetection())
.build();

} catch (Exception e) {
log.error("获取ThreadLocal统计信息失败", e);
throw new ThreadLocalException("获取ThreadLocal统计信息失败: " + e.getMessage());
}
}

/**
* 销毁ThreadLocal管理器
*/
@PreDestroy
public void destroy() {
try {
// 清理所有ThreadLocal
clearAll();

// 清理资源
threadLocalMap.clear();

log.info("ThreadLocal管理器销毁完成");

} catch (Exception e) {
log.error("ThreadLocal管理器销毁失败", e);
}
}
}

2.2 上下文管理器

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
/**
* 上下文管理器
* 负责管理各种上下文信息
*/
@Component
@Slf4j
public class ContextManager {

private final Map<String, Object> contextMap = new ConcurrentHashMap<>();
private final ThreadLocal<Map<String, Object>> threadLocalContext = new ThreadLocal<>();

/**
* 设置用户上下文
*/
public void setUserContext(UserContext userContext) {
try {
String key = "userContext";
setContext(key, userContext);

// 设置到ThreadLocal
setThreadLocalContext(key, userContext);

log.debug("用户上下文设置成功: {}", userContext.getUserId());

} catch (Exception e) {
log.error("用户上下文设置失败", e);
throw new ContextException("用户上下文设置失败: " + e.getMessage());
}
}

/**
* 获取用户上下文
*/
public UserContext getUserContext() {
try {
String key = "userContext";
UserContext userContext = getContext(key, UserContext.class);

if (userContext == null) {
// 从ThreadLocal获取
userContext = getThreadLocalContext(key, UserContext.class);
}

return userContext;

} catch (Exception e) {
log.error("用户上下文获取失败", e);
throw new ContextException("用户上下文获取失败: " + e.getMessage());
}
}

/**
* 设置请求上下文
*/
public void setRequestContext(RequestContext requestContext) {
try {
String key = "requestContext";
setContext(key, requestContext);

// 设置到ThreadLocal
setThreadLocalContext(key, requestContext);

log.debug("请求上下文设置成功: {}", requestContext.getRequestId());

} catch (Exception e) {
log.error("请求上下文设置失败", e);
throw new ContextException("请求上下文设置失败: " + e.getMessage());
}
}

/**
* 获取请求上下文
*/
public RequestContext getRequestContext() {
try {
String key = "requestContext";
RequestContext requestContext = getContext(key, RequestContext.class);

if (requestContext == null) {
// 从ThreadLocal获取
requestContext = getThreadLocalContext(key, RequestContext.class);
}

return requestContext;

} catch (Exception e) {
log.error("请求上下文获取失败", e);
throw new ContextException("请求上下文获取失败: " + e.getMessage());
}
}

/**
* 设置业务上下文
*/
public void setBusinessContext(String businessKey, Object businessValue) {
try {
String key = "businessContext_" + businessKey;
setContext(key, businessValue);

// 设置到ThreadLocal
setThreadLocalContext(key, businessValue);

log.debug("业务上下文设置成功: {} = {}", businessKey, businessValue);

} catch (Exception e) {
log.error("业务上下文设置失败: {}", businessKey, e);
throw new ContextException("业务上下文设置失败: " + e.getMessage());
}
}

/**
* 获取业务上下文
*/
public <T> T getBusinessContext(String businessKey, Class<T> type) {
try {
String key = "businessContext_" + businessKey;
T businessValue = getContext(key, type);

if (businessValue == null) {
// 从ThreadLocal获取
businessValue = getThreadLocalContext(key, type);
}

return businessValue;

} catch (Exception e) {
log.error("业务上下文获取失败: {}", businessKey, e);
throw new ContextException("业务上下文获取失败: " + e.getMessage());
}
}

/**
* 设置安全上下文
*/
public void setSecurityContext(SecurityContext securityContext) {
try {
String key = "securityContext";
setContext(key, securityContext);

// 设置到ThreadLocal
setThreadLocalContext(key, securityContext);

log.debug("安全上下文设置成功: {}", securityContext.getPrincipal());

} catch (Exception e) {
log.error("安全上下文设置失败", e);
throw new ContextException("安全上下文设置失败: " + e.getMessage());
}
}

/**
* 获取安全上下文
*/
public SecurityContext getSecurityContext() {
try {
String key = "securityContext";
SecurityContext securityContext = getContext(key, SecurityContext.class);

if (securityContext == null) {
// 从ThreadLocal获取
securityContext = getThreadLocalContext(key, SecurityContext.class);
}

return securityContext;

} catch (Exception e) {
log.error("安全上下文获取失败", e);
throw new ContextException("安全上下文获取失败: " + e.getMessage());
}
}

/**
* 设置日志上下文
*/
public void setLogContext(LogContext logContext) {
try {
String key = "logContext";
setContext(key, logContext);

// 设置到ThreadLocal
setThreadLocalContext(key, logContext);

log.debug("日志上下文设置成功: {}", logContext.getTraceId());

} catch (Exception e) {
log.error("日志上下文设置失败", e);
throw new ContextException("日志上下文设置失败: " + e.getMessage());
}
}

/**
* 获取日志上下文
*/
public LogContext getLogContext() {
try {
String key = "logContext";
LogContext logContext = getContext(key, LogContext.class);

if (logContext == null) {
// 从ThreadLocal获取
logContext = getThreadLocalContext(key, LogContext.class);
}

return logContext;

} catch (Exception e) {
log.error("日志上下文获取失败", e);
throw new ContextException("日志上下文获取失败: " + e.getMessage());
}
}

/**
* 设置上下文
*/
private void setContext(String key, Object value) {
contextMap.put(key, value);
}

/**
* 获取上下文
*/
private <T> T getContext(String key, Class<T> type) {
Object value = contextMap.get(key);
if (value != null && type.isAssignableFrom(value.getClass())) {
return type.cast(value);
}
return null;
}

/**
* 设置ThreadLocal上下文
*/
private void setThreadLocalContext(String key, Object value) {
Map<String, Object> threadContext = threadLocalContext.get();
if (threadContext == null) {
threadContext = new HashMap<>();
threadLocalContext.set(threadContext);
}
threadContext.put(key, value);
}

/**
* 获取ThreadLocal上下文
*/
private <T> T getThreadLocalContext(String key, Class<T> type) {
Map<String, Object> threadContext = threadLocalContext.get();
if (threadContext != null) {
Object value = threadContext.get(key);
if (value != null && type.isAssignableFrom(value.getClass())) {
return type.cast(value);
}
}
return null;
}

/**
* 记录上下文信息
*/
public void recordContext(String name, Object value) {
try {
String key = "record_" + name;
setThreadLocalContext(key, value);

} catch (Exception e) {
log.error("记录上下文信息失败: {}", name, e);
}
}

/**
* 清理上下文信息
*/
public void clearContext(String name) {
try {
String key = "record_" + name;
Map<String, Object> threadContext = threadLocalContext.get();
if (threadContext != null) {
threadContext.remove(key);
}

} catch (Exception e) {
log.error("清理上下文信息失败: {}", name, e);
}
}

/**
* 清理所有上下文
*/
public void clearAllContext() {
try {
contextMap.clear();
threadLocalContext.remove();

log.info("所有上下文清理完成");

} catch (Exception e) {
log.error("清理所有上下文失败", e);
}
}

/**
* 获取上下文统计信息
*/
public ContextStatistics getContextStatistics() {
try {
Map<String, Object> threadContext = threadLocalContext.get();
int threadLocalContextSize = threadContext != null ? threadContext.size() : 0;

return ContextStatistics.builder()
.totalContextCount(contextMap.size())
.threadLocalContextCount(threadLocalContextSize)
.contextKeys(new ArrayList<>(contextMap.keySet()))
.build();

} catch (Exception e) {
log.error("获取上下文统计信息失败", e);
throw new ContextException("获取上下文统计信息失败: " + e.getMessage());
}
}
}

2.3 内存管理器

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
/**
* 内存管理器
* 负责ThreadLocal的内存管理和泄漏检测
*/
@Component
@Slf4j
public class MemoryManager {

private final Map<String, ThreadLocal<?>> registeredThreadLocals = new ConcurrentHashMap<>();
private final Map<String, Object> valueHistory = new ConcurrentHashMap<>();
private final AtomicLong totalSetCount = new AtomicLong(0);
private final AtomicLong totalGetCount = new AtomicLong(0);
private final AtomicLong totalRemoveCount = new AtomicLong(0);

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
private final MemoryAnalyzer memoryAnalyzer;

/**
* 注册ThreadLocal
*/
public void registerThreadLocal(String name, ThreadLocal<?> threadLocal) {
try {
registeredThreadLocals.put(name, threadLocal);

// 启动内存监控
startMemoryMonitoring(name);

log.info("ThreadLocal注册成功: {}", name);

} catch (Exception e) {
log.error("ThreadLocal注册失败: {}", name, e);
throw new MemoryException("ThreadLocal注册失败: " + e.getMessage());
}
}

/**
* 记录设置操作
*/
public void recordSet(String name, Object value) {
try {
totalSetCount.incrementAndGet();
valueHistory.put(name + "_lastSet", value);
valueHistory.put(name + "_setTime", System.currentTimeMillis());

// 检查内存使用情况
checkMemoryUsage(name, value);

} catch (Exception e) {
log.error("记录设置操作失败: {}", name, e);
}
}

/**
* 记录获取操作
*/
public void recordGet(String name) {
try {
totalGetCount.incrementAndGet();
valueHistory.put(name + "_getTime", System.currentTimeMillis());

} catch (Exception e) {
log.error("记录获取操作失败: {}", name, e);
}
}

/**
* 记录移除操作
*/
public void recordRemove(String name, Object value) {
try {
totalRemoveCount.incrementAndGet();
valueHistory.put(name + "_lastRemove", value);
valueHistory.put(name + "_removeTime", System.currentTimeMillis());

} catch (Exception e) {
log.error("记录移除操作失败: {}", name, e);
}
}

/**
* 启动内存监控
*/
private void startMemoryMonitoring(String name) {
scheduler.scheduleAtFixedRate(() -> {
try {
monitorThreadLocalMemory(name);
} catch (Exception e) {
log.error("ThreadLocal内存监控失败: {}", name, e);
}
}, 0, 30, TimeUnit.SECONDS);
}

/**
* 监控ThreadLocal内存
*/
private void monitorThreadLocalMemory(String name) {
try {
ThreadLocal<?> threadLocal = registeredThreadLocals.get(name);
if (threadLocal == null) {
return;
}

// 检查内存使用情况
long memoryUsage = getThreadLocalMemoryUsage(name);

// 检查是否超过阈值
if (memoryUsage > getMemoryThreshold()) {
log.warn("ThreadLocal内存使用超过阈值: {} = {}", name, memoryUsage);

// 触发垃圾回收
triggerGarbageCollection(name);
}

// 检查泄漏
checkMemoryLeak(name);

} catch (Exception e) {
log.error("ThreadLocal内存监控失败: {}", name, e);
}
}

/**
* 检查内存使用情况
*/
private void checkMemoryUsage(String name, Object value) {
try {
if (value == null) {
return;
}

// 估算对象大小
long objectSize = estimateObjectSize(value);

// 检查是否超过单个对象阈值
if (objectSize > getSingleObjectThreshold()) {
log.warn("ThreadLocal对象大小超过阈值: {} = {}", name, objectSize);
}

} catch (Exception e) {
log.error("检查内存使用情况失败: {}", name, e);
}
}

/**
* 检查内存泄漏
*/
private void checkMemoryLeak(String name) {
try {
ThreadLocal<?> threadLocal = registeredThreadLocals.get(name);
if (threadLocal == null) {
return;
}

// 检查ThreadLocal是否还有值
Object value = threadLocal.get();
if (value != null) {
// 检查值是否长时间未更新
Long lastSetTime = (Long) valueHistory.get(name + "_setTime");
if (lastSetTime != null) {
long timeSinceLastSet = System.currentTimeMillis() - lastSetTime;
if (timeSinceLastSet > getLeakDetectionThreshold()) {
log.warn("检测到ThreadLocal可能泄漏: {} = {}", name, timeSinceLastSet);

// 触发清理
triggerCleanup(name);
}
}
}

} catch (Exception e) {
log.error("检查内存泄漏失败: {}", name, e);
}
}

/**
* 触发垃圾回收
*/
private void triggerGarbageCollection(String name) {
try {
// 建议JVM进行垃圾回收
System.gc();

log.info("触发垃圾回收: {}", name);

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

/**
* 触发清理
*/
private void triggerCleanup(String name) {
try {
ThreadLocal<?> threadLocal = registeredThreadLocals.get(name);
if (threadLocal != null) {
threadLocal.remove();
log.info("触发ThreadLocal清理: {}", name);
}

} catch (Exception e) {
log.error("触发清理失败: {}", name, e);
}
}

/**
* 获取ThreadLocal内存使用情况
*/
private long getThreadLocalMemoryUsage(String name) {
try {
// 这里可以使用JVM内存分析工具
// 简化实现,返回估算值
return memoryAnalyzer.analyzeMemoryUsage(name);

} catch (Exception e) {
log.error("获取ThreadLocal内存使用情况失败: {}", name, e);
return 0;
}
}

/**
* 估算对象大小
*/
private long estimateObjectSize(Object value) {
try {
// 简化实现,返回估算值
if (value instanceof String) {
return ((String) value).length() * 2; // 每个字符2字节
} else if (value instanceof Collection) {
return ((Collection<?>) value).size() * 16; // 每个元素16字节
} else if (value instanceof Map) {
return ((Map<?, ?>) value).size() * 32; // 每个键值对32字节
} else {
return 64; // 默认64字节
}

} catch (Exception e) {
log.error("估算对象大小失败", e);
return 0;
}
}

/**
* 获取内存阈值
*/
private long getMemoryThreshold() {
// 默认1MB
return 1024 * 1024;
}

/**
* 获取单个对象阈值
*/
private long getSingleObjectThreshold() {
// 默认100KB
return 100 * 1024;
}

/**
* 获取泄漏检测阈值
*/
private long getLeakDetectionThreshold() {
// 默认5分钟
return 5 * 60 * 1000;
}

/**
* 获取内存使用情况
*/
public MemoryUsage getMemoryUsage() {
try {
return MemoryUsage.builder()
.totalSetCount(totalSetCount.get())
.totalGetCount(totalGetCount.get())
.totalRemoveCount(totalRemoveCount.get())
.registeredThreadLocalCount(registeredThreadLocals.size())
.valueHistorySize(valueHistory.size())
.build();

} catch (Exception e) {
log.error("获取内存使用情况失败", e);
throw new MemoryException("获取内存使用情况失败: " + e.getMessage());
}
}

/**
* 清理内存管理器
*/
@PreDestroy
public void cleanup() {
try {
scheduler.shutdown();
registeredThreadLocals.clear();
valueHistory.clear();

log.info("内存管理器清理完成");

} catch (Exception e) {
log.error("内存管理器清理失败", e);
}
}
}

三、性能监控与泄漏检测

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
/**
* 性能监控器
* 负责监控ThreadLocal的性能指标
*/
@Component
@Slf4j
public class PerformanceMonitor {

private final Map<String, PerformanceMetrics> metricsMap = new ConcurrentHashMap<>();
private final AtomicLong totalOperations = new AtomicLong(0);
private final AtomicLong totalLatency = new AtomicLong(0);

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

/**
* 记录操作
*/
public void recordOperation(String name, String operation) {
try {
totalOperations.incrementAndGet();

PerformanceMetrics metrics = metricsMap.computeIfAbsent(name, k ->
PerformanceMetrics.builder()
.name(k)
.setCount(0)
.getCount(0)
.removeCount(0)
.totalLatency(0)
.averageLatency(0)
.maxLatency(0)
.minLatency(Long.MAX_VALUE)
.lastOperationTime(System.currentTimeMillis())
.build()
);

long startTime = System.nanoTime();

// 更新指标
updateMetrics(metrics, operation);

long endTime = System.nanoTime();
long latency = endTime - startTime;

totalLatency.addAndGet(latency);
metrics.setTotalLatency(metrics.getTotalLatency() + latency);
metrics.setAverageLatency(metrics.getTotalLatency() / getTotalOperationCount(metrics));
metrics.setMaxLatency(Math.max(metrics.getMaxLatency(), latency));
metrics.setMinLatency(Math.min(metrics.getMinLatency(), latency));
metrics.setLastOperationTime(System.currentTimeMillis());

} catch (Exception e) {
log.error("记录操作失败: {} - {}", name, operation, e);
}
}

/**
* 更新指标
*/
private void updateMetrics(PerformanceMetrics metrics, String operation) {
switch (operation) {
case "set":
metrics.setSetCount(metrics.getSetCount() + 1);
break;
case "get":
metrics.setGetCount(metrics.getGetCount() + 1);
break;
case "remove":
metrics.setRemoveCount(metrics.getRemoveCount() + 1);
break;
}
}

/**
* 获取总操作次数
*/
private long getTotalOperationCount(PerformanceMetrics metrics) {
return metrics.getSetCount() + metrics.getGetCount() + metrics.getRemoveCount();
}

/**
* 获取性能指标
*/
public Map<String, PerformanceMetrics> getMetrics() {
return new HashMap<>(metricsMap);
}

/**
* 获取总体性能指标
*/
public OverallPerformanceMetrics getOverallMetrics() {
try {
long totalOps = totalOperations.get();
long totalLat = totalLatency.get();
double averageLatency = totalOps > 0 ? (double) totalLat / totalOps : 0;

return OverallPerformanceMetrics.builder()
.totalOperations(totalOps)
.totalLatency(totalLat)
.averageLatency(averageLatency)
.threadLocalCount(metricsMap.size())
.build();

} catch (Exception e) {
log.error("获取总体性能指标失败", e);
throw new PerformanceException("获取总体性能指标失败: " + e.getMessage());
}
}

/**
* 启动性能监控
*/
@PostConstruct
public void startMonitoring() {
scheduler.scheduleAtFixedRate(() -> {
try {
logPerformanceMetrics();
} catch (Exception e) {
log.error("性能监控失败", e);
}
}, 0, 60, TimeUnit.SECONDS);
}

/**
* 记录性能指标
*/
private void logPerformanceMetrics() {
try {
OverallPerformanceMetrics overallMetrics = getOverallMetrics();

log.info("ThreadLocal性能指标 - 总操作数: {}, 平均延迟: {}ns, ThreadLocal数量: {}",
overallMetrics.getTotalOperations(),
overallMetrics.getAverageLatency(),
overallMetrics.getThreadLocalCount());

// 记录每个ThreadLocal的性能指标
for (PerformanceMetrics metrics : metricsMap.values()) {
log.debug("ThreadLocal性能指标 - {}: 设置={}, 获取={}, 移除={}, 平均延迟={}ns",
metrics.getName(),
metrics.getSetCount(),
metrics.getGetCount(),
metrics.getRemoveCount(),
metrics.getAverageLatency());
}

} catch (Exception e) {
log.error("记录性能指标失败", e);
}
}

/**
* 清理性能监控器
*/
@PreDestroy
public void cleanup() {
try {
scheduler.shutdown();
metricsMap.clear();

log.info("性能监控器清理完成");

} catch (Exception e) {
log.error("性能监控器清理失败", e);
}
}
}

3.2 泄漏检测器

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
/**
* 泄漏检测器
* 负责检测ThreadLocal内存泄漏
*/
@Component
@Slf4j
public class LeakDetector {

private final Map<String, LeakDetectionInfo> leakDetectionMap = new ConcurrentHashMap<>();
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

private final AtomicLong totalLeakCount = new AtomicLong(0);
private final AtomicLong totalDetectionCount = new AtomicLong(0);

/**
* 检测ThreadLocal泄漏
*/
public LeakDetectionResult detectLeak(String name, ThreadLocal<?> threadLocal) {
try {
totalDetectionCount.incrementAndGet();

LeakDetectionInfo info = leakDetectionMap.computeIfAbsent(name, k ->
LeakDetectionInfo.builder()
.name(k)
.threadLocal(threadLocal)
.firstDetectionTime(System.currentTimeMillis())
.lastDetectionTime(System.currentTimeMillis())
.detectionCount(0)
.leakCount(0)
.build()
);

// 更新检测信息
info.setLastDetectionTime(System.currentTimeMillis());
info.setDetectionCount(info.getDetectionCount() + 1);

// 检测泄漏
boolean isLeaked = performLeakDetection(info);

if (isLeaked) {
info.setLeakCount(info.getLeakCount() + 1);
totalLeakCount.incrementAndGet();

log.warn("检测到ThreadLocal泄漏: {}", name);
}

return LeakDetectionResult.builder()
.name(name)
.isLeaked(isLeaked)
.leakCount(info.getLeakCount())
.detectionCount(info.getDetectionCount())
.lastDetectionTime(info.getLastDetectionTime())
.build();

} catch (Exception e) {
log.error("检测ThreadLocal泄漏失败: {}", name, e);
throw new LeakDetectionException("检测ThreadLocal泄漏失败: " + e.getMessage());
}
}

/**
* 执行泄漏检测
*/
private boolean performLeakDetection(LeakDetectionInfo info) {
try {
ThreadLocal<?> threadLocal = info.getThreadLocal();

// 检查ThreadLocal是否有值
Object value = threadLocal.get();
if (value == null) {
return false; // 没有值,不是泄漏
}

// 检查值是否长时间未更新
long timeSinceLastDetection = System.currentTimeMillis() - info.getLastDetectionTime();
if (timeSinceLastDetection > getLeakThreshold()) {
return true; // 长时间未更新,可能是泄漏
}

// 检查值的大小
long valueSize = estimateValueSize(value);
if (valueSize > getSizeThreshold()) {
return true; // 值过大,可能是泄漏
}

// 检查值的类型
if (isLeakProneType(value)) {
return true; // 容易泄漏的类型
}

return false;

} catch (Exception e) {
log.error("执行泄漏检测失败: {}", info.getName(), e);
return false;
}
}

/**
* 估算值的大小
*/
private long estimateValueSize(Object value) {
try {
if (value instanceof String) {
return ((String) value).length() * 2;
} else if (value instanceof Collection) {
return ((Collection<?>) value).size() * 16;
} else if (value instanceof Map) {
return ((Map<?, ?>) value).size() * 32;
} else if (value instanceof byte[]) {
return ((byte[]) value).length;
} else {
return 64; // 默认大小
}

} catch (Exception e) {
log.error("估算值大小失败", e);
return 0;
}
}

/**
* 检查是否是容易泄漏的类型
*/
private boolean isLeakProneType(Object value) {
try {
// 检查是否是容易泄漏的类型
if (value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
return collection.size() > 1000; // 集合过大
} else if (value instanceof Map) {
Map<?, ?> map = (Map<?, ?>) value;
return map.size() > 1000; // Map过大
} else if (value instanceof byte[]) {
byte[] bytes = (byte[]) value;
return bytes.length > 1024 * 1024; // 字节数组过大
}

return false;

} catch (Exception e) {
log.error("检查泄漏类型失败", e);
return false;
}
}

/**
* 获取泄漏阈值
*/
private long getLeakThreshold() {
// 默认10分钟
return 10 * 60 * 1000;
}

/**
* 获取大小阈值
*/
private long getSizeThreshold() {
// 默认1MB
return 1024 * 1024;
}

/**
* 获取泄漏检测信息
*/
public LeakDetectionInfo getLeakDetectionInfo(String name) {
return leakDetectionMap.get(name);
}

/**
* 获取所有泄漏检测信息
*/
public Map<String, LeakDetectionInfo> getAllLeakDetectionInfo() {
return new HashMap<>(leakDetectionMap);
}

/**
* 获取泄漏检测统计
*/
public LeakDetectionStatistics getLeakDetectionStatistics() {
try {
long totalLeaks = totalLeakCount.get();
long totalDetections = totalDetectionCount.get();
double leakRate = totalDetections > 0 ? (double) totalLeaks / totalDetections : 0;

return LeakDetectionStatistics.builder()
.totalLeakCount(totalLeaks)
.totalDetectionCount(totalDetections)
.leakRate(leakRate)
.detectionInfoCount(leakDetectionMap.size())
.build();

} catch (Exception e) {
log.error("获取泄漏检测统计失败", e);
throw new LeakDetectionException("获取泄漏检测统计失败: " + e.getMessage());
}
}

/**
* 启动泄漏检测
*/
@PostConstruct
public void startLeakDetection() {
scheduler.scheduleAtFixedRate(() -> {
try {
performPeriodicLeakDetection();
} catch (Exception e) {
log.error("定期泄漏检测失败", e);
}
}, 0, 5, TimeUnit.MINUTES);
}

/**
* 执行定期泄漏检测
*/
private void performPeriodicLeakDetection() {
try {
for (LeakDetectionInfo info : leakDetectionMap.values()) {
LeakDetectionResult result = detectLeak(info.getName(), info.getThreadLocal());

if (result.isLeaked()) {
log.warn("定期检测发现ThreadLocal泄漏: {} - 泄漏次数: {}",
result.getName(), result.getLeakCount());
}
}

} catch (Exception e) {
log.error("执行定期泄漏检测失败", e);
}
}

/**
* 清理泄漏检测器
*/
@PreDestroy
public void cleanup() {
try {
scheduler.shutdown();
leakDetectionMap.clear();

log.info("泄漏检测器清理完成");

} catch (Exception e) {
log.error("泄漏检测器清理失败", e);
}
}
}

四、ThreadLocal配置与管理

4.1 ThreadLocal配置

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
/**
* ThreadLocal配置
*/
@Configuration
@EnableConfigurationProperties(ThreadLocalProperties.class)
@Slf4j
public class ThreadLocalConfiguration {

private final ThreadLocalProperties properties;

/**
* ThreadLocal管理器
*/
@Bean
@ConditionalOnMissingBean
public ThreadLocalManager threadLocalManager(
MemoryManager memoryManager,
PerformanceMonitor performanceMonitor,
LeakDetector leakDetector,
ContextManager contextManager) {

return new ThreadLocalManager(
memoryManager,
performanceMonitor,
leakDetector,
contextManager
);
}

/**
* 上下文管理器
*/
@Bean
@ConditionalOnMissingBean
public ContextManager contextManager() {
return new ContextManager();
}

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

/**
* 性能监控器
*/
@Bean
@ConditionalOnMissingBean
public PerformanceMonitor performanceMonitor() {
return new PerformanceMonitor();
}

/**
* 泄漏检测器
*/
@Bean
@ConditionalOnMissingBean
public LeakDetector leakDetector() {
return new LeakDetector();
}

/**
* 内存分析器
*/
@Bean
@ConditionalOnMissingBean
public MemoryAnalyzer memoryAnalyzer() {
return new MemoryAnalyzer();
}

/**
* ThreadLocal管理端点
*/
@Bean
@ConditionalOnProperty(name = "thread-local.management.endpoints.enabled", havingValue = "true", matchIfMissing = true)
public ThreadLocalManagementEndpoint threadLocalManagementEndpoint(
ThreadLocalManager threadLocalManager) {

return new ThreadLocalManagementEndpoint(threadLocalManager);
}
}

4.2 ThreadLocal属性配置

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
/**
* ThreadLocal属性配置
*/
@ConfigurationProperties(prefix = "thread-local")
@Data
@Slf4j
public class ThreadLocalProperties {

/**
* 是否启用ThreadLocal管理
*/
private boolean enabled = true;

/**
* 是否启用内存管理
*/
private boolean enableMemoryManagement = true;

/**
* 是否启用性能监控
*/
private boolean enablePerformanceMonitoring = true;

/**
* 是否启用泄漏检测
*/
private boolean enableLeakDetection = true;

/**
* 是否启用上下文管理
*/
private boolean enableContextManagement = true;

/**
* 内存管理配置
*/
private MemoryManagementConfig memoryManagement = new MemoryManagementConfig();

/**
* 性能监控配置
*/
private PerformanceMonitoringConfig performanceMonitoring = new PerformanceMonitoringConfig();

/**
* 泄漏检测配置
*/
private LeakDetectionConfig leakDetection = new LeakDetectionConfig();

/**
* 上下文管理配置
*/
private ContextManagementConfig contextManagement = new ContextManagementConfig();

/**
* 内存管理配置
*/
@Data
public static class MemoryManagementConfig {
/**
* 内存阈值(字节)
*/
private long memoryThreshold = 1024 * 1024; // 1MB

/**
* 单个对象阈值(字节)
*/
private long singleObjectThreshold = 100 * 1024; // 100KB

/**
* 泄漏检测阈值(毫秒)
*/
private long leakDetectionThreshold = 5 * 60 * 1000; // 5分钟

/**
* 监控间隔(秒)
*/
private int monitoringInterval = 30;

/**
* 是否启用自动清理
*/
private boolean enableAutoCleanup = true;

/**
* 清理间隔(分钟)
*/
private int cleanupInterval = 10;
}

/**
* 性能监控配置
*/
@Data
public static class PerformanceMonitoringConfig {
/**
* 是否启用性能监控
*/
private boolean enabled = true;

/**
* 监控间隔(秒)
*/
private int monitoringInterval = 60;

/**
* 是否启用延迟监控
*/
private boolean enableLatencyMonitoring = true;

/**
* 是否启用吞吐量监控
*/
private boolean enableThroughputMonitoring = true;

/**
* 延迟阈值(纳秒)
*/
private long latencyThreshold = 1000000; // 1ms
}

/**
* 泄漏检测配置
*/
@Data
public static class LeakDetectionConfig {
/**
* 是否启用泄漏检测
*/
private boolean enabled = true;

/**
* 检测间隔(分钟)
*/
private int detectionInterval = 5;

/**
* 泄漏阈值(毫秒)
*/
private long leakThreshold = 10 * 60 * 1000; // 10分钟

/**
* 大小阈值(字节)
*/
private long sizeThreshold = 1024 * 1024; // 1MB

/**
* 是否启用自动清理
*/
private boolean enableAutoCleanup = true;
}

/**
* 上下文管理配置
*/
@Data
public static class ContextManagementConfig {
/**
* 是否启用上下文管理
*/
private boolean enabled = true;

/**
* 是否启用用户上下文
*/
private boolean enableUserContext = true;

/**
* 是否启用请求上下文
*/
private boolean enableRequestContext = true;

/**
* 是否启用业务上下文
*/
private boolean enableBusinessContext = true;

/**
* 是否启用安全上下文
*/
private boolean enableSecurityContext = true;

/**
* 是否启用日志上下文
*/
private boolean enableLogContext = true;

/**
* 上下文超时时间(分钟)
*/
private int contextTimeout = 30;
}
}

五、ThreadLocal管理端点

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
/**
* ThreadLocal管理端点
* 提供RESTful API进行ThreadLocal管理
*/
@RestController
@RequestMapping("/api/thread-local")
@Slf4j
public class ThreadLocalManagementEndpoint {

private final ThreadLocalManager threadLocalManager;

/**
* 创建ThreadLocal
*/
@PostMapping("/create")
public ResponseEntity<ThreadLocalInfo> createThreadLocal(
@Valid @RequestBody CreateThreadLocalRequest request) {

try {
ThreadLocal<?> threadLocal = threadLocalManager.createThreadLocal(
request.getName(), request.getType());

ThreadLocalInfo info = ThreadLocalInfo.builder()
.name(request.getName())
.type(request.getType().getSimpleName())
.hasValue(threadLocal.get() != null)
.build();

return ResponseEntity.ok(info);
} catch (Exception e) {
log.error("创建ThreadLocal失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 设置ThreadLocal值
*/
@PostMapping("/set")
public ResponseEntity<Void> setThreadLocalValue(
@Valid @RequestBody SetThreadLocalValueRequest request) {

try {
threadLocalManager.setValue(request.getName(), request.getValue());
return ResponseEntity.ok().build();
} catch (Exception e) {
log.error("设置ThreadLocal值失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 获取ThreadLocal值
*/
@GetMapping("/get/{name}")
public ResponseEntity<Object> getThreadLocalValue(@PathVariable String name) {
try {
Object value = threadLocalManager.getValue(name);
return ResponseEntity.ok(value);
} catch (Exception e) {
log.error("获取ThreadLocal值失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 移除ThreadLocal值
*/
@DeleteMapping("/remove/{name}")
public ResponseEntity<Void> removeThreadLocalValue(@PathVariable String name) {
try {
threadLocalManager.removeValue(name);
return ResponseEntity.ok().build();
} catch (Exception e) {
log.error("移除ThreadLocal值失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 清理所有ThreadLocal
*/
@PostMapping("/clear-all")
public ResponseEntity<Void> clearAllThreadLocals() {
try {
threadLocalManager.clearAll();
return ResponseEntity.ok().build();
} catch (Exception e) {
log.error("清理所有ThreadLocal失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 获取ThreadLocal统计信息
*/
@GetMapping("/statistics")
public ResponseEntity<ThreadLocalStatistics> getThreadLocalStatistics() {
try {
ThreadLocalStatistics statistics = threadLocalManager.getStatistics();
return ResponseEntity.ok(statistics);
} catch (Exception e) {
log.error("获取ThreadLocal统计信息失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 获取性能指标
*/
@GetMapping("/performance")
public ResponseEntity<OverallPerformanceMetrics> getPerformanceMetrics() {
try {
OverallPerformanceMetrics metrics = threadLocalManager.getPerformanceMetrics();
return ResponseEntity.ok(metrics);
} catch (Exception e) {
log.error("获取性能指标失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 获取泄漏检测信息
*/
@GetMapping("/leak-detection")
public ResponseEntity<LeakDetectionStatistics> getLeakDetectionStatistics() {
try {
LeakDetectionStatistics statistics = threadLocalManager.getLeakDetectionStatistics();
return ResponseEntity.ok(statistics);
} catch (Exception e) {
log.error("获取泄漏检测信息失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 导出ThreadLocal报告
*/
@GetMapping("/export")
public ResponseEntity<byte[]> exportThreadLocalReport(
@RequestParam(defaultValue = "pdf") String format) {

try {
byte[] report = threadLocalManager.exportThreadLocalReport(format);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "thread-local-report." + format);
return ResponseEntity.ok().headers(headers).body(report);
} catch (Exception e) {
log.error("导出ThreadLocal报告失败", e);
return ResponseEntity.badRequest().build();
}
}
}

六、实战应用与最佳实践

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
/**
* 用户上下文管理实战示例
*/
@RestController
@RequestMapping("/api/user-context")
@Slf4j
public class UserContextManagementExample {

private final ThreadLocalManager threadLocalManager;
private final ContextManager contextManager;

/**
* 设置用户上下文
*/
@PostMapping("/set-user-context")
public ResponseEntity<Void> setUserContext(@Valid @RequestBody UserContextRequest request) {
try {
// 创建用户上下文
UserContext userContext = UserContext.builder()
.userId(request.getUserId())
.username(request.getUsername())
.email(request.getEmail())
.roles(request.getRoles())
.permissions(request.getPermissions())
.loginTime(System.currentTimeMillis())
.build();

// 设置到ThreadLocal
threadLocalManager.setValue("userContext", userContext);

// 设置到上下文管理器
contextManager.setUserContext(userContext);

log.info("用户上下文设置成功: {}", request.getUserId());
return ResponseEntity.ok().build();

} catch (Exception e) {
log.error("设置用户上下文失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 获取用户上下文
*/
@GetMapping("/get-user-context")
public ResponseEntity<UserContext> getUserContext() {
try {
// 从ThreadLocal获取
UserContext userContext = threadLocalManager.getValue("userContext");

if (userContext == null) {
// 从上下文管理器获取
userContext = contextManager.getUserContext();
}

return ResponseEntity.ok(userContext);

} catch (Exception e) {
log.error("获取用户上下文失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 清理用户上下文
*/
@PostMapping("/clear-user-context")
public ResponseEntity<Void> clearUserContext() {
try {
// 清理ThreadLocal
threadLocalManager.removeValue("userContext");

// 清理上下文管理器
contextManager.clearAllContext();

log.info("用户上下文清理成功");
return ResponseEntity.ok().build();

} catch (Exception e) {
log.error("清理用户上下文失败", e);
return ResponseEntity.badRequest().build();
}
}

/**
* 获取当前用户信息
*/
@GetMapping("/current-user")
public ResponseEntity<CurrentUserInfo> getCurrentUser() {
try {
UserContext userContext = getUserContext().getBody();

if (userContext == null) {
return ResponseEntity.notFound().build();
}

CurrentUserInfo currentUser = CurrentUserInfo.builder()
.userId(userContext.getUserId())
.username(userContext.getUsername())
.email(userContext.getEmail())
.roles(userContext.getRoles())
.permissions(userContext.getPermissions())
.loginTime(userContext.getLoginTime())
.sessionDuration(System.currentTimeMillis() - userContext.getLoginTime())
.build();

return ResponseEntity.ok(currentUser);

} catch (Exception e) {
log.error("获取当前用户信息失败", e);
return ResponseEntity.badRequest().build();
}
}
}

6.2 ThreadLocal最佳实践

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
/**
* ThreadLocal最佳实践
*/
@Component
@Slf4j
public class ThreadLocalBestPractices {

private final ThreadLocalManager threadLocalManager;

/**
* ThreadLocal最佳实践指南
*/
public void demonstrateBestPractices() {
log.info("=== ThreadLocal最佳实践指南 ===");

// 1. 正确使用ThreadLocal
demonstrateCorrectUsage();

// 2. 避免内存泄漏
demonstrateMemoryLeakPrevention();

// 3. 性能优化
demonstratePerformanceOptimization();

// 4. 上下文管理
demonstrateContextManagement();

// 5. 监控和调试
demonstrateMonitoringAndDebugging();
}

/**
* 正确使用ThreadLocal
*/
private void demonstrateCorrectUsage() {
log.info("--- 正确使用ThreadLocal ---");

try {
// 1. 使用静态变量
ThreadLocal<String> staticThreadLocal = threadLocalManager.createThreadLocal(
"staticThreadLocal", String.class);

// 2. 设置初始值
staticThreadLocal.set("初始值");

// 3. 获取值
String value = staticThreadLocal.get();
log.info("ThreadLocal值: {}", value);

// 4. 及时清理
staticThreadLocal.remove();

log.info("ThreadLocal使用示例完成");

} catch (Exception e) {
log.error("ThreadLocal使用示例失败", e);
}
}

/**
* 避免内存泄漏
*/
private void demonstrateMemoryLeakPrevention() {
log.info("--- 避免内存泄漏 ---");

try {
// 1. 使用弱引用
ThreadLocal<Map<String, Object>> weakThreadLocal = threadLocalManager.createThreadLocal(
"weakThreadLocal", Map.class);

// 2. 避免在ThreadLocal中存储大对象
Map<String, Object> smallMap = new HashMap<>();
smallMap.put("key1", "value1");
smallMap.put("key2", "value2");
weakThreadLocal.set(smallMap);

// 3. 及时清理
weakThreadLocal.remove();

log.info("内存泄漏防护示例完成");

} catch (Exception e) {
log.error("内存泄漏防护示例失败", e);
}
}

/**
* 性能优化
*/
private void demonstratePerformanceOptimization() {
log.info("--- 性能优化 ---");

try {
// 1. 使用缓存
ThreadLocal<Map<String, Object>> cacheThreadLocal = threadLocalManager.createThreadLocal(
"cacheThreadLocal", Map.class);

// 2. 避免频繁创建对象
Map<String, Object> cache = cacheThreadLocal.get();
if (cache == null) {
cache = new HashMap<>();
cacheThreadLocal.set(cache);
}

// 3. 使用对象池
ThreadLocal<StringBuilder> stringBuilderThreadLocal = threadLocalManager.createThreadLocal(
"stringBuilderThreadLocal", StringBuilder.class);

StringBuilder sb = stringBuilderThreadLocal.get();
if (sb == null) {
sb = new StringBuilder();
stringBuilderThreadLocal.set(sb);
} else {
sb.setLength(0); // 重置
}

log.info("性能优化示例完成");

} catch (Exception e) {
log.error("性能优化示例失败", e);
}
}

/**
* 上下文管理
*/
private void demonstrateContextManagement() {
log.info("--- 上下文管理 ---");

try {
// 1. 用户上下文
UserContext userContext = UserContext.builder()
.userId("12345")
.username("testuser")
.email("test@example.com")
.roles(Arrays.asList("USER", "ADMIN"))
.permissions(Arrays.asList("READ", "WRITE"))
.loginTime(System.currentTimeMillis())
.build();

threadLocalManager.setValue("userContext", userContext);

// 2. 请求上下文
RequestContext requestContext = RequestContext.builder()
.requestId(UUID.randomUUID().toString())
.requestTime(System.currentTimeMillis())
.clientIp("192.168.1.1")
.userAgent("Mozilla/5.0")
.build();

threadLocalManager.setValue("requestContext", requestContext);

// 3. 业务上下文
Map<String, Object> businessContext = new HashMap<>();
businessContext.put("orderId", "ORDER-12345");
businessContext.put("amount", 100.0);
businessContext.put("currency", "USD");

threadLocalManager.setValue("businessContext", businessContext);

log.info("上下文管理示例完成");

} catch (Exception e) {
log.error("上下文管理示例失败", e);
}
}

/**
* 监控和调试
*/
private void demonstrateMonitoringAndDebugging() {
log.info("--- 监控和调试 ---");

try {
// 1. 获取统计信息
ThreadLocalStatistics statistics = threadLocalManager.getStatistics();
log.info("ThreadLocal统计信息: {}", statistics);

// 2. 获取性能指标
OverallPerformanceMetrics performanceMetrics = threadLocalManager.getPerformanceMetrics();
log.info("性能指标: {}", performanceMetrics);

// 3. 获取泄漏检测信息
LeakDetectionStatistics leakDetectionStatistics = threadLocalManager.getLeakDetectionStatistics();
log.info("泄漏检测统计: {}", leakDetectionStatistics);

// 4. 导出报告
byte[] report = threadLocalManager.exportThreadLocalReport("json");
log.info("报告导出完成,大小: {} bytes", report.length);

log.info("监控和调试示例完成");

} catch (Exception e) {
log.error("监控和调试示例失败", e);
}
}
}

七、总结

本文深入探讨了SpringBoot中ThreadLocal的架构设计与实战应用。通过构建企业级的ThreadLocal管理框架,我们实现了:

  1. 线程隔离与上下文传递:为每个线程提供独立的变量副本,实现线程间的数据隔离
  2. 内存泄漏防护:通过自动清理、泄漏检测等技术,有效防止内存泄漏问题
  3. 性能监控与优化:提供全面的性能监控和优化机制,确保ThreadLocal的高效使用
  4. 上下文管理:支持用户上下文、请求上下文、业务上下文等多种上下文类型
  5. 企业级管理:提供完整的配置管理、监控告警、报告导出等功能

通过这套企业级的ThreadLocal架构,我们能够安全高效地管理线程本地变量,实现线程间的数据隔离和上下文传递。随着微服务架构和高并发系统的不断发展,构建可扩展、可维护的ThreadLocal框架将成为企业级架构师必须掌握的核心技能。

在实际应用中,建议遵循ThreadLocal的最佳实践,及时清理资源,避免内存泄漏,并通过监控和调试工具确保系统的稳定运行。只有这样,才能真正发挥ThreadLocal的价值,构建高质量的企业级应用系统。