Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SecurityContextHolder.getContext() NPE when using @Async

I'm trying to convert a sequential series of calls of spring service to be asynchronous.

I have annotated the method with @Async and added taskExecutor configuratinos.

I can see that the method is now being invoked asynchronously but I'm having issues with SecurityContextHolder.getContext() throwing this error:

java.util.concurrent.ExecutionException: java.lang.NullPointerException

Would really appreciate any insights. Thanks!

like image 845
Assaf Karmon Avatar asked Jun 05 '26 03:06

Assaf Karmon


1 Answers

The SecurityContext is stored in a ThreadLocal. So if you access it from a new thread that didn't set it anywhere, then the SecurityContext is null.

Update: Added Threadlocal javadoc link

like image 93
Brian Kent Avatar answered Jun 07 '26 18:06

Brian Kent