RequestContextHolder 是线程安全的吗?

2024-04-27

在我的 Spring JDBC 项目中,我有一个名为DBStuff我用它来连接到数据库并进行简单的数据库操作。这是一个Web项目,有用户,所以自然我使用会话机制。当我需要检索请求数据时DBStuff类,我使用下面这行代码:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

但是,没有任何解释表明如果RequestContextHolder是否线程安全。就连春天的官方forum https://web.archive.org/web/20170828054346/http://forum.spring.io/forum/spring-projects/web/web-flow/748410-requestcontextholder-thread-local对此没有答案。由于使用servlet,我需要为用户提供线程安全的特性。

根据定义RequestContextHolder被定义为“Holder 类以线程绑定的形式公开 Web 请求RequestAttributes对象。”但我不确定“线程绑定”是否代表线程安全。


“线程绑定”意味着每个线程都有自己的数据副本,因此它是线程安全的。

It uses ThreadLocal为了那个原因

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()回报RequestAttributes对于当前线程来说,它是处理一个HTTP要求。每个请求都有一个自己的线程。

Method get() of ThreadLocal使用映射将数据绑定到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();
}

我应该何时以及如何使用 ThreadLocal 变量? https://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RequestContextHolder 是线程安全的吗? 的相关文章

随机推荐