Parallel Threads with Spring Context
Parallel Threads with Spring Context
We are developing a piece of code and in that we are executing bunch of methods in sequence, and these method are not working on a shared resource so we thought converting that to a parallel might help us with the execution time, so we used FixedThreadPool, however we started seeing some issues with Spring Security Context not available in the methods which are executed in these threads.
There were no errors, but more runtime errors where information we expect wasn’t available, and luckily previous build worked fine and after doing a diff we found only code change we did was to use ThreadPool and digging further we noticed spring context is missing.
Luckily SecurityContextHolder which holds our spring security Authentication object has a property to enable this in inheritable threads via MODE_INHERITABLETHREADLOCAL
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);