0 day streak
java / expert
Snippet

Custom Thread-Local Scope Implementation

Custom Scopes allow developers to manage bean lifecycles beyond 'singleton' or 'prototype'. A ThreadScope is an expert pattern used in high-concurrency scenarios to ensure state is isolated per execution thread without passing parameters.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ThreadScope implements Scope {
private final ThreadLocal<Map<String, Object>> threadObjects = ThreadLocal.withInitial(HashMap::new);
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
return threadObjects.get().computeIfAbsent(name, k -> objectFactory.getObject());
}
@Override
public Object remove(String name) {
return threadObjects.get().remove(name);
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {}
@Override
public String getConversationId() {
return Thread.currentThread().getName();
}
}
spring
Breakdown
1
implements Scope
The core SPI for extending Spring's bean lifecycle management.
2
threadObjects.get().computeIfAbsent(...)
Uses a ThreadLocal map to store and retrieve bean instances, ensuring thread isolation.