Question

I know that every request is served by a servlet thread, but will it be possible for one user session, two request served by two different thread?

If the situation above really happens, what about thread local variable stored by first request-serving thread be read by second request-serving thread?

I'm afraid that if I store user credential in Spring Security's SecurityContextHolder(which uses thread local variable) in first thread, the second thread will not be able to access the user credential...

Was it helpful?

Solution

I know that every request is served by a servlet thread, but will it be possible for one user session, two request served by two different thread?

Yes, that's possible.

I'm afraid that if I store user credential in Spring Security's SecurityContextHolder(which uses thread local variable) in first thread, the second thread will not be able to access the user credential...

Security is established separately for each request by Spring, you do not have to handle this yourself.

OTHER TIPS

No, one request will not be served by several threads. What can really happen is serving of 2 requests by one thread. This is the reason that you should be very careful using thread local variables yourself. However you can trust Spring framework: it does things right. It can for example use session or request ID when using thread local, so 2 request being processed by one thread will not be confused.

Two separate requests of the same user are handled (most likely) by two different threads.

I am not sure what Spring does, but the Servlet api provides a way to retrieve data that is specific to the user session (how the server tracks the session is irrelevant, but have a look at cookies and url rewriting).

Now, If I wanted to have the user credentials on a threadlocal variable (which is not unusual, as the ThreadLocal pseudo-singleton is the most convenient way of injection I know), I would store them on the users HttpSession (which is persistent across all requests of the same user) and use a servlet filter to put them on the threadlocal at the beginning of each request.

I hope this makes things a bit clearer for you. I find it is better to know what's happening under the hood even when using the most up to date framework :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top