Why doesn't spring provide a thread scope implementation?

multithreading, scope, spring

Solution

Spring does provide a thread scope, but it is not registered by default.

The existing bean scopes are defined in the documentation, here.

singleton

- (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype

- Scopes a single bean definition to any number of object instances.

request

- Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring `ApplicationContext`.

session

- Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. global

application

- Scopes a single bean definition to the lifecycle of a `ServletContext`. Only valid in the context of a web-aware Spring `ApplicationContext`.

websocket

- Scopes a single bean definition to the lifecycle of a `WebSocket`. Only valid in the context of a web-aware Spring `ApplicationContext`.

The documentation then makes a note

As of Spring 3.0, a thread scope is available, but is not registered by default. For more information, see the documentation for `SimpleThreadScope`.

Note that, similarly to the prototype scope, the thread scope

[`SimpleThreadScope`] does not clean up any objects associated with it.

This thread scope implementation uses a `ThreadLocal` to store beans. You cannot detect a `Thread` ending/dying in Java, so the Spring IOC container cannot explicitly know when to remove the beans from the `ThreadLocal` and invoke any end of lifecycle methods. That responsibility then falls on the developer.

Be careful where you use this scope. For example, in a thread pooling context, a bean might already have been created and stored in one of the pools' reused threads. Depending on your use case, that might be the incorrect behavior.

Problem

Why doesn't Spring provide a thread scope implementation? Has anyone used thread scoped beans with Spring in a web application context? There should be a standard, clear description of how to do this! (SpringByExample has a solution—I didn't test it—but it is not mainstream yet.)

Original source