| Issue 114: | Thread scope for Guice | |
| 3 people starred this issue and may be notified of changes. | Back to list |
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. |
|
,
Jun 25, 2007
Besides the reasons in issue #100 , the Spring Framework has a similar ticket with some other use cases: http://opensource.atlassian.com/projects/spring/browse/SPR-2581 |
|
,
Nov 14, 2008
We're not going to include it in the source 'cause it's quite an advanced feature. But SimpleScope is here: http://code.google.com/p/google-guice/wiki/Scopes
Status: WontFix
|
|
,
Oct 05, 2009
I think that thread scope is extremely useful, especially in web application ans should be build in Guice :-( |
|
,
Oct 05, 2009
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. |
|
,
Oct 05, 2009
The major problem with the built-in request-scope is that it requires an HttpServletRequest. Not all requests come in this form, thus the scope can only be used in certain cases. Having a general purpose request-scope implementation (ThreadLocal based, or otherwise) would be very useful. Bob - any suggestions on alternate implementations? |
|
|
|