Issue
Given the following configuration:
@Configuration
class TLConfig {
@Bean
fun foo() = tl.getOrSet { Foo("something") }
private val tl = ThreadLocal<Foo>()
}
- Will there only be one instance of
Foo
created or will there be an instance created for each thread that wants the bean? - If only one instance created, what happens when different threads try to use it?
DISCLAIMER: I am not looking for suggestions of what to do instead. I just want to know how this code would behave. I am not suggesting that this is a good or bad way to do things, it is just something I found, and I have no idea what the behavior is.
Solution
It creates one instance (default scope is singleton) and put it into the application context. So when you inject it, it will comes from there, no matter which thread ask the dependency. The foo
function only called once, when the bean is initialized.
Answered By - zlaval
Answer Checked By - David Goodson (JavaFixing Volunteer)