I use spring security in my project.
I have feature to change login. To achieve this aim I use following code
Authentication authentication = ...
SecurityContextHolder.getContext().setAuthentication(authentication);
But now I am resesarching this code in details and see that authentication field is not volatile
thus visibility is not guaranteed:
public class SecurityContextImpl implements SecurityContext {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
// ~ Instance fields
// ================================================================================================
private Authentication authentication;
Should I wrap my code with my own synchronization to achieve visibility?
P.S.
I have read https://stackoverflow.com/a/30781541/2674303
In an application which receives concurrent requests in a single session, the same SecurityContext instance will be shared between threads. Even though a ThreadLocal is being used, it is the same instance that is retrieved from the HttpSession for each thread. This has implications if you wish to temporarily change the context under which a thread is running. If you just use SecurityContextHolder.getContext(), and call setAuthentication(anAuthentication) on the returned context object, then the Authentication object will change in all concurrent threads which share the same SecurityContext instance. You can customize the behaviour of SecurityContextPersistenceFilter to create a completely new SecurityContext for each request, preventing changes in one thread from affecting another. Alternatively you can create a new instance just at the point where you temporarily change the context. The method SecurityContextHolder.createEmptyContext() always returns a new context instance.
but I don't understand how spring does guaranties visibility. There are just written that each thread within session will see changes. but there is no answer how fast? and more important - visibility mechanism is not explained