Guice Thread Scope

June 7, 2007
UPDATE: The reset thing turned out to be a bad idea, I created simple Thread Scope instead. If you somehow seem to need a reset, consider this.

Ever wanted to use Guice's request scope outside of a web application? Try out my thread scope implementation and let me know what you think. Cast your vote if you want to see this scope added to Guice.

Here's an example. Create a Module that looks like this:

Injector i = Guice.createInjector(new Module() {
public void configure(Binder binder) {
binder.bindScope(ThreadScoped.class, CustomScopes.THREAD);
// add your custom classes

Each thread is automatically initialized for the scope. To reset it, use the ThreadCache:
@Inject private ThreadCache threadCache
public void someMethod() {
try {
// do stuff in thread scope
} finally {

I'm thinking about loading this scope's initialization code lazily (so that you'll need to execute threadCache.start() or something like that). It currently doesn't matter for me and the memory overhead is low anyway, but what do you think?

PS: only use field injection for examples ;-)