Take the 2-minute tour ×

I have a web application running on Google App Engine (GAE) for JAVA. I'm authenticating the client at the Servlet layer but would like to make the client information available to my business and data layers without having to pass the client object through the arguments of every single function.

I'm considering setting up a "session" type object using ThreadLocal. That way any function can just say something like:


Is this a good way to do this or is there something else that is a more accepted solution?


share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

This will probably work and will be utterly convenient, but usually I try to avoid ThreadLocals for similar use cases as much as I can. Reasons:

  • You code just suddenly starts to depend on the fact that underlying container uses different threads for different users. If the container will start using NIO, different type of threads (e.g. green threads which would not be mapped into java.lang.Thread on some exotic JVM), etc. you will be out of luck.

  • ThreadLocals tend to be forgotten to be cleaned up after using them. So if your server will spike in usage and one of the users will put lots of stuff into 'cache', you might run out of RAM.

  • As a consequence of not cleaning up after a request, ThreadLocal can expose security vulnerability assuming the other user would jump unto the same thread.

  • Finally, I believe ThreadLocals were designed for environments where you have an absolute control over threads in your context, and this use case is just so far beyond.

Unfortunately I don't know much about GAE to suggest a viable alternative, sorry about that!

share|improve this answer
Good answer, but I don't think the first point is true as long as he sticks to the interface he suggested - CurrentUser.getRoles does not presuppose using a thread local specifically. –  Nick Johnson Nov 21 '11 at 3:23
add comment

ThreadLocals are a completely accepted way to store such information. Besides us I also know from Alfresco that they do it.

share|improve this answer
add comment

If using Spring and Spring Security works for you then you can use the code I've built as part of jappstart for your authentication/authorization. This information is then available via Spring Security.

share|improve this answer
add comment

Your Answer


