首页 > 编程语言 > 详细

聊一聊Spring中的线程安全性

时间:2019-03-05 20:50:59      阅读:191      评论:0      收藏:0      [点我收藏+]

Spring作为一个IOC/DI容器,帮助我们管理了许许多多的“bean”。但其实,Spring并没有保证这些对象的线程安全,需要由开发者自己编写解决线程安全问题的代码。

Spring对每个bean提供了一个scope属性来表示该bean的作用域。它是bean的生命周期。例如,一个scope为singleton的bean,在第一次被注入时,会创建为一个单例对象,该对象会一直被复用到应用结束。

  • singleton:默认的scope,每个scope为singleton的bean都会被定义为一个单例对象,该对象的生命周期是与Spring IOC容器一致的(但在第一次被注入时才会创建)。

  • prototype:bean被定义为在每次注入时都会创建一个新的对象。

  • request:bean被定义为在每个HTTP请求中创建一个单例对象,也就是说在单个请求中都会复用这一个单例对象。

  • session:bean被定义为在一个session的生命周期内创建一个单例对象。

  • application:bean被定义为在ServletContext的生命周期中复用一个单例对象。

  • websocket:bean被定义为在websocket的生命周期中复用一个单例对象。

我们交由Spring管理的大多数对象其实都是一些无状态的对象,这种不会因为多线程而导致状态被破坏的对象很适合Spring的默认scope,每个单例的无状态对象都是线程安全的(也可以说只要是无状态的对象,不管单例多例都是线程安全的,不过单例毕竟节省了不断创建对象与GC的开销)。

无状态的对象即是自身没有状态的对象,自然也就不会因为多个线程的交替调度而破坏自身状态导致线程安全问题。无状态对象包括我们经常使用的DO、DTO、VO这些只作为数据的实体模型的贫血对象,还有Service、DAO和Controller,这些对象并没有自己的状态,它们只是用来执行某些操作的。例如,每个DAO提供的函数都只是对数据库的CRUD,而且每个数据库Connection都作为函数的局部变量(局部变量是在用户栈中的,而且用户栈本身就是线程私有的内存区域,所以不存在线程安全问题),用完即关(或交还给连接池)。

有人可能会认为,我使用request作用域不就可以避免每个请求之间的安全问题了吗?这是完全错误的,因为Controller默认是单例的,一个HTTP请求是会被多个线程执行的,这就又回到了线程的安全问题。当然,你也可以把Controller的scope改成prototype,实际上Struts2就是这么做的,但有一点要注意,Spring MVC对请求的拦截粒度是基于每个方法的,而Struts2是基于每个类的,所以把Controller设为多例将会频繁的创建与回收对象,严重影响到了性能。

通过阅读上文其实已经说的很清楚了,Spring根本就没有对bean的多线程安全问题做出任何保证与措施。对于每个bean的线程安全问题,根本原因是每个bean自身的设计。不要在bean中声明任何有状态的实例变量或类变量,如果必须如此,那么就使用ThreadLocal把变量变为线程私有的,如果bean的实例变量或类变量需要在多个线程之间共享,那么就只能使用synchronized、lock、CAS等这些实现线程同步的方法了。

下面将通过解析ThreadLocal的源码来了解它的实现与作用,ThreadLocal是一个很好用的工具类,它在某些情况下解决了线程安全问题(在变量不需要被多个线程共享时)。

本文作者为SylvanasSun(sylvanas.sun@gmail.com),首发于SylvanasSun’s Blog
原文链接:sylvanassun.github.io/2017/11/06/…
(转载请务必保留本段声明,并且保留超链接。)

ThreadLocal


ThreadLocal是一个为线程提供线程局部变量的工具类。它的思想也十分简单,就是为线程提供一个线程私有的变量副本,这样多个线程都可以随意更改自己线程局部的变量,不会影响到其他线程。不过需要注意的是,ThreadLocal提供的只是一个浅拷贝,如果变量是一个引用类型,那么就要考虑它内部的状态是否会被改变,想要解决这个问题可以通过重写ThreadLocal的initialValue()函数来自己实现深拷贝,建议在使用ThreadLocal时一开始就重写该函数。

ThreadLocal与像synchronized这样的锁机制是不同的。首先,它们的应用场景与实现思路就不一样,锁更强调的是如何同步多个线程去正确地共享一个变量,ThreadLocal则是为了解决同一个变量如何不被多个线程共享。从性能开销的角度上来讲,如果锁机制是用时间换空间的话,那么ThreadLocal就是用空间换时间。

ThreadLocal中含有一个叫做ThreadLocalMap的内部类,该类为一个采用线性探测法实现的HashMap。它的key为ThreadLocal对象而且还使用了WeakReference,ThreadLocalMap正是用来存储变量副本的。

 1 /**
 2      * ThreadLocalMap is a customized hash map suitable only for
 3      * maintaining thread local values. No operations are exported
 4      * outside of the ThreadLocal class. The class is package private to
 5      * allow declaration of fields in class Thread.  To help deal with
 6      * very large and long-lived usages, the hash table entries use
 7      * WeakReferences for keys. However, since reference queues are not
 8      * used, stale entries are guaranteed to be removed only when
 9      * the table starts running out of space.
10      */
11     static class ThreadLocalMap {
12         /**
13          * The entries in this hash map extend WeakReference, using
14          * its main ref field as the key (which is always a
15          * ThreadLocal object).  Note that null keys (i.e. entry.get()
16          * == null) mean that the key is no longer referenced, so the
17          * entry can be expunged from table.  Such entries are referred to
18          * as "stale entries" in the code that follows.
19          */
20         static class Entry extends WeakReference<ThreadLocal<?>> {
21             /** The value associated with this ThreadLocal. */
22             Object value;
23 
24             Entry(ThreadLocal<?> k, Object v) {
25                 super(k);
26                 value = v;
27             }
28         }
29         ....
30     }
 

ThreadLocal中只含有三个成员变量,这三个变量都是与ThreadLocalMap的hash策略相关的。

 1  /**
 2      * ThreadLocals rely on per-thread linear-probe hash maps attached
 3      * to each thread (Thread.threadLocals and
 4      * inheritableThreadLocals).  The ThreadLocal objects act as keys,
 5      * searched via threadLocalHashCode.  This is a custom hash code
 6      * (useful only within ThreadLocalMaps) that eliminates collisions
 7      * in the common case where consecutively constructed ThreadLocals
 8      * are used by the same threads, while remaining well-behaved in
 9      * less common cases.
10      */
11     private final int threadLocalHashCode = nextHashCode();
12 
13     /**
14      * The next hash code to be given out. Updated atomically. Starts at
15      * zero.
16      */
17     private static AtomicInteger nextHashCode =
18         new AtomicInteger();
19 
20     /**
21      * The difference between successively generated hash codes - turns
22      * implicit sequential thread-local IDs into near-optimally spread
23      * multiplicative hash values for power-of-two-sized tables.
24      */
25     private static final int HASH_INCREMENT = 0x61c88647;
26 
27     /**
28      * Returns the next hash code.
29      */
30     private static int nextHashCode() {
31         return nextHashCode.getAndAdd(HASH_INCREMENT);
32     }

唯一的实例变量threadLocalHashCode是用来进行寻址的hashcode,它由函数nextHashCode()生成,该函数简单地通过一个增量HASH_INCREMENT来生成hashcode。至于为什么这个增量为0x61c88647,主要是因为ThreadLocalMap的初始大小为16,每次扩容都会为原来的2倍,这样它的容量永远为2的n次方,该增量选为0x61c88647也是为了尽可能均匀地分布,减少碰撞冲突。

 1 /**
 2          * The initial capacity -- MUST be a power of two.
 3          */
 4         private static final int INITIAL_CAPACITY = 16;    
 5 
 6         /**
 7          * Construct a new map initially containing (firstKey, firstValue).
 8          * ThreadLocalMaps are constructed lazily, so we only create
 9          * one when we have at least one entry to put in it.
10          */
11         ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
12             table = new Entry[INITIAL_CAPACITY];
13             int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
14             table[i] = new Entry(firstKey, firstValue);
15             size = 1;
16             setThreshold(INITIAL_CAPACITY);
17         }

要获得当前线程私有的变量副本需要调用get()函数。首先,它会调用getMap()函数去获得当前线程的ThreadLocalMap,这个函数需要接收当前线程的实例作为参数。如果得到的ThreadLocalMap为null,那么就去调用setInitialValue()函数来进行初始化,如果不为null,就通过map来获得变量副本并返回。

setInitialValue()函数会去先调用initialValue()函数来生成初始值,该函数默认返回null,我们可以通过重写这个函数来返回我们想要在ThreadLocal中维护的变量。之后,去调用getMap()函数获得ThreadLocalMap,如果该map已经存在,那么就用新获得value去覆盖旧值,否则就调用createMap()函数来创建新的map。

 1 /**
 2      * Returns the value in the current thread‘s copy of this
 3      * thread-local variable.  If the variable has no value for the
 4      * current thread, it is first initialized to the value returned
 5      * by an invocation of the {@link #initialValue} method.
 6      *
 7      * @return the current thread‘s value of this thread-local
 8      */
 9     public T get() {
10         Thread t = Thread.currentThread();
11         ThreadLocalMap map = getMap(t);
12         if (map != null) {
13             ThreadLocalMap.Entry e = map.getEntry(this);
14             if (e != null) {
15                 @SuppressWarnings("unchecked")
16                 T result = (T)e.value;
17                 return result;
18             }
19         }
20         return setInitialValue();
21     }
22 
23     /**
24      * Variant of set() to establish initialValue. Used instead
25      * of set() in case user has overridden the set() method.
26      *
27      * @return the initial value
28      */
29     private T setInitialValue() {
30         T value = initialValue();
31         Thread t = Thread.currentThread();
32         ThreadLocalMap map = getMap(t);
33         if (map != null)
34             map.set(this, value);
35         else
36             createMap(t, value);
37         return value;
38     }
39 
40     protected T initialValue() {
41         return null;
42     }

ThreadLocal的set()与remove()函数要比get()的实现还要简单,都只是通过getMap()来获得ThreadLocalMap然后对其进行操作。

 1 /**
 2      * Sets the current thread‘s copy of this thread-local variable
 3      * to the specified value.  Most subclasses will have no need to
 4      * override this method, relying solely on the {@link #initialValue}
 5      * method to set the values of thread-locals.
 6      *
 7      * @param value the value to be stored in the current thread‘s copy of
 8      *        this thread-local.
 9      */
10     public void set(T value) {
11         Thread t = Thread.currentThread();
12         ThreadLocalMap map = getMap(t);
13         if (map != null)
14             map.set(this, value);
15         else
16             createMap(t, value);
17     }
18 
19     /**
20      * Removes the current thread‘s value for this thread-local
21      * variable.  If this thread-local variable is subsequently
22      * {@linkplain #get read} by the current thread, its value will be
23      * reinitialized by invoking its {@link #initialValue} method,
24      * unless its value is {@linkplain #set set} by the current thread
25      * in the interim.  This may result in multiple invocations of the
26      * {@code initialValue} method in the current thread.
27      *
28      * @since 1.5
29      */
30      public void remove() {
31          ThreadLocalMap m = getMap(Thread.currentThread());
32          if (m != null)
33              m.remove(this);
34      }

getMap()函数与createMap()函数的实现也十分简单,但是通过观察这两个函数可以发现一个秘密:ThreadLocalMap是存放在Thread中的。

 1 /**
 2      * Get the map associated with a ThreadLocal. Overridden in
 3      * InheritableThreadLocal.
 4      *
 5      * @param  t the current thread
 6      * @return the map
 7      */
 8     ThreadLocalMap getMap(Thread t) {
 9         return t.threadLocals;
10     }
11 
12     /**
13      * Create the map associated with a ThreadLocal. Overridden in
14      * InheritableThreadLocal.
15      *
16      * @param t the current thread
17      * @param firstValue value for the initial entry of the map
18      */
19     void createMap(Thread t, T firstValue) {
20         t.threadLocals = new ThreadLocalMap(this, firstValue);
21     }
22 
23     // Thread中的源码
24 
25     /* ThreadLocal values pertaining to this thread. This map is maintained
26      * by the ThreadLocal class. */
27     ThreadLocal.ThreadLocalMap threadLocals = null;
28 
29     /*
30      * InheritableThreadLocal values pertaining to this thread. This map is
31      * maintained by the InheritableThreadLocal class.
32      */
33     ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

仔细想想其实就能够理解这种设计的思想。有一种普遍的方法是通过一个全局的线程安全的Map来存储各个线程的变量副本,但是这种做法已经完全违背了ThreadLocal的本意,设计ThreadLocal的初衷就是为了避免多个线程去并发访问同一个对象,尽管它是线程安全的。而在每个Thread中存放与它关联的ThreadLocalMap是完全符合ThreadLocal的思想的,当想要对线程局部变量进行操作时,只需要把Thread作为key来获得Thread中的ThreadLocalMap即可。这种设计相比采用一个全局Map的方法会多占用很多内存空间,但也因此不需要额外的采取锁等线程同步方法而节省了时间上的消耗。

ThreadLocal中的内存泄漏


我们要考虑一种会发生内存泄漏的情况,如果ThreadLocal被设置为null后,而且没有任何强引用指向它,根据垃圾回收的可达性分析算法,ThreadLocal将会被回收。这样一来,ThreadLocalMap中就会含有key为null的Entry,而且ThreadLocalMap是在Thread中的,只要线程迟迟不结束,这些无法访问到的value会形成内存泄漏。为了解决这个问题,ThreadLocalMap中的getEntry()、set()和remove()函数都会清理key为null的Entry,以下面的getEntry()函数的源码为例。

 1 /**
 2          * Get the entry associated with key.  This method
 3          * itself handles only the fast path: a direct hit of existing
 4          * key. It otherwise relays to getEntryAfterMiss.  This is
 5          * designed to maximize performance for direct hits, in part
 6          * by making this method readily inlinable.
 7          *
 8          * @param  key the thread local object
 9          * @return the entry associated with key, or null if no such
10          */
11         private Entry getEntry(ThreadLocal<?> key) {
12             int i = key.threadLocalHashCode & (table.length - 1);
13             Entry e = table[i];
14             if (e != null && e.get() == key)
15                 return e;
16             else
17                 return getEntryAfterMiss(key, i, e);
18         }
19 
20         /**
21          * Version of getEntry method for use when key is not found in
22          * its direct hash slot.
23          *
24          * @param  key the thread local object
25          * @param  i the table index for key‘s hash code
26          * @param  e the entry at table[i]
27          * @return the entry associated with key, or null if no such
28          */
29         private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
30             Entry[] tab = table;
31             int len = tab.length;
32 
33             // 清理key为null的Entry
34             while (e != null) {
35                 ThreadLocal<?> k = e.get();
36                 if (k == key)
37                     return e;
38                 if (k == null)
39                     expungeStaleEntry(i);
40                 else
41                     i = nextIndex(i, len);
42                 e = tab[i];
43             }
44             return null;
45         }

在上文中我们发现了ThreadLocalMap的key是一个弱引用,那么为什么使用弱引用呢?使用强引用key与弱引用key的差别如下:

  • 强引用key:ThreadLocal被设置为null,由于ThreadLocalMap持有ThreadLocal的强引用,如果不手动删除,那么ThreadLocal将不会回收,产生内存泄漏。

  • 弱引用key:ThreadLocal被设置为null,由于ThreadLocalMap持有ThreadLocal的弱引用,即便不手动删除,ThreadLocal仍会被回收,ThreadLocalMap在之后调用set()、getEntry()和remove()函数时会清除所有key为null的Entry。

但要注意的是,ThreadLocalMap仅仅含有这些被动措施来补救内存泄漏问题。如果你在之后没有调用ThreadLocalMap的set()、getEntry()和remove()函数的话,那么仍然会存在内存泄漏问题。

在使用线程池的情况下,如果不及时进行清理,内存泄漏问题事小,甚至还会产生程序逻辑上的问题。所以,为了安全地使用ThreadLocal,必须要像每次使用完锁就解锁一样,在每次使用完ThreadLocal后都要调用remove()来清理无用的Entry。



聊一聊Spring中的线程安全性

原文:https://www.cnblogs.com/fnlingnzb-learner/p/10479184.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!