Harshana
Harshana

Reputation: 7647

Singleton bean with ThreadLocal variable bahavior

I have a bean with default singleton scope. This bean is access by many threads and I want student object to be specific to each thread. I am using spring boot with rest

In such implementation, how does singleton bean handles student objects set by different threads. Does spring return same A object to each thread but with customize object value for student variable?

@Service
class A{

 private InheritableThreadLocal<Student> student;

}

Upvotes: 0

Views: 2463

Answers (1)

Sajith Edirisinghe
Sajith Edirisinghe

Reputation: 1727

Spring will create only one instance object of the class A (let's call it objA) and within that object, the thread local variable will reside. Note that, Spring doesn't return the objA to any thread, but the threads executes the logic within or associated with objA.

However, the Threadlocal variable value is only visible to the thread which is executing the logic. In this case even there is only one object instance of class A (objA) each executing thread will have its own value for the thread local variable student according to ThreadLocal javadoc,

These variables differ from their normal counterparts in that each thread that accesses one (via its {@code get} or {@code set} method) has its own, independently initialized copy of the variable

Note that in here you have used InheritableThreadLocal and according to its java doc

This class extends ThreadLocal to provide inheritance of values from parent thread to child thread: when a child thread is created, the child receives initial values for all inheritable thread-local variables for which the parent has values.

So if you set the thread local value in the parent thread, same value will be available in the child thread. However, you can modify the thread local value in the child thread, but it will not affect the thread local value of the parent thread.

Be careful when using thread locals. If you are using a thread pool, it is a must to clean thread locals at the correct time. Otherwise thread local leaks will occur.

Upvotes: 2

Related Questions