Issue
In my Spring JDBC project I have a class called DBStuff
which i use to connect to DB and make simple DB operations. It's a web project and there are users, so naturally i use session mechanism. When i need to retrieve request data in DBStuff
class, I use this line of code below:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
But, there is no explanation that if the RequestContextHolder
is thread-safe or not. Even the spring's official forum doesn't have an answer for that. Because of using servlet, I need to provide a thread-safe nature for the users.
By definition RequestContextHolder
is defined as "Holder class to expose the web request in the form of a thread-bound RequestAttributes
object." But I am not sure if "thread-bound" stands for thread-safe.
Solution
"thread-bound" means that every thread has own copy of the data, so it is thread-safe.
It uses ThreadLocal
for that
private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
new NamedThreadLocal<RequestAttributes>("Request attributes");
public static RequestAttributes getRequestAttributes() {
RequestAttributes attributes = requestAttributesHolder.get();
if (attributes == null) {
attributes = inheritableRequestAttributesHolder.get();
}
return attributes;
}
requestAttributesHolder.get()
returns RequestAttributes
for the current thread, it is a thread that process an HTTP
request. Every request has an own thread.
Method get()
of ThreadLocal
uses a map to bound the data to the Thread.currentThread()
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
When and how should I use a ThreadLocal variable?
Answered By - v.ladynev
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)