Thread scope for Guice
See original GitHub issueFrom robbie.vanbrabant on June 08, 2007 06:26:25
As a follow-up to issue #100 , Guice could support a pure Thread scope:
public static final Scope THREAD = new Scope() {
public <T> Provider<T> scope(final Key<T> key, final Provider<T>
creator) {
return new Provider<T>() {
public T get() {
ThreadLocalCache cache = ThreadLocalCache.getInstance();
T value = cache.get(key);
if (value == null) {
value = creator.get();
cache.add(key, value);
}
return value;
}
};
}
};
private static final class ThreadLocalCache {
private Map<Key<?>, Object> map = new HashMap<Key<?>, Object>();
// use lazy init to avoid memory overhead when not using the scope?
private static final ThreadLocal<ThreadLocalCache> THREAD_LOCAL =
new ThreadLocal<ThreadLocalCache>() {
@
Override protected ThreadLocalCache initialValue() {
return new ThreadLocalCache();
}
};
// suppress warnings because the add method
// captures the type
@
SuppressWarnings(“unchecked”)
public <T> T get(Key<T> key) {
return (T) map.get(key);
}
public <T> void add(Key<T> key, T value) {
map.put(key, value);
}
public static ThreadLocalCache getInstance() {
return THREAD_LOCAL.get();
}
}
As Kevin said, it could be useful when using classes that are not thread safe, like SimpleDateFormat.
_Original issue: http://code.google.com/p/google-guice/issues/detail?id=114_
Issue Analytics
- State:
- Created 9 years ago
- Comments:12
Top GitHub Comments
From crazyboblee on October 05, 2009 11:48:35
Guice has request scope which is similar but better. The problem with the impl above (and just about any thread scope impl) is that it doesn’t remove the thread local values, so it will leak memory in many cases.
Thanks @GedMarc. Will check 😃