問題
在開發過程中,我們一旦在某個類中使用一個可變的成員變量,就會涉及到線程安全問題,因爲我們的類對於其他依賴使用類來說,可能是單例注入的,這就會涉及到多個線程共享操作同一個變量問題。如何解決?
遇到線程安全問題,我們首先想到的就是使用鎖
,萬物可加鎖,只要不怕慢!我們通過加鎖來實現多個線程併發訪問操作問題,我加鎖,你就得等我解鎖後才能操作。但是衆所周知,加鎖,必定會在多線程併發訪問時造成一部分線程阻塞等待,從而產生一定的性能影響。那除了加鎖,有沒有其他方法來避免?答案是:有滴!我們可以使用多種方式,下面我們娓娓道來~
ThreadLocal方式
介紹
ThreadLocal
從字面理解就是本地線程,全稱:Thread Local Variable
。換句話說,就是當前線程變量,它是一個本地線程變量,其填充的是當前線程
的變量,這個變量對於其他線程來說都是封閉且隔離的
。- 如何實現變量隔離這一功能?
ThreadLocal
可以爲每個線程創建一個自有副本,每個線程可以訪問自己內部的副本變量來達到隔離效果,從而解決共享變量的線程安全問題。 ThreadLocal
變量是線程內部的局部變量,在不同的線程Thread中有不同的副本,副本只能由當前Thread使用,不存在多線程共享問題。ThreadLocal
一般由private static
修飾,線程結束時,可回收掉ThreadLocal
副本。
案例
之前在SpringBoot—集成AOP詳解(面向切面編程Aspect)中的AOP編碼中也是用到了ThreadLocal
進行starttime
變量的存儲。
源碼
set方法
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
//獲取當前線程
Thread t = Thread.currentThread();
//獲取當前線程中的變量map
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
//若爲空,則初始化當前線程的變量map,key爲當前線程,map爲變量
createMap(t, value);
}
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
//弱引用,若爲null時,ThreadLocal被回收,但是map的value還存在,容易造成內存泄漏
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
//使用Entry保存數據,k爲ThreadLocal,v爲變量value值
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table.
*/
private int size = 0;
...
//其他源碼省略
...
/**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
}
ThreadLocalMap
是ThreadLocal
的一個靜態內部類,使用Entry
保存數據。Entry
繼承WeakReference
弱引用,key爲當前線程ThreadLocal
,value爲變量值。
get方法
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
//獲取當前線程
Thread t = Thread.currentThread();
//獲取變量map
ThreadLocalMap map = getMap(t);
if (map != null) {
//從獲取Entry
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
內存泄漏問題
原因
ThreadLocal
是弱引用,若爲null
時,ThreadLocal
被回收(這樣可以避免Entry
內存泄漏)。- 雖然
ThreadLocalMap
保存的ThreadLocal
弱引用被回收了,但的value
還存在,容易造成內存泄漏。
引用
強引用
:強引用的對象,不會被回收。如直接new
一個對象,就算OOM異常,也不會回收該對象。軟引用
:軟引用的對象,只有發生gc時,發現內存不足,纔會回收。如緩存,系統內存充足時,一般不會回收對象,當系統內存不足且gc時,就會回收這些軟引用對象。弱引用
:弱引用的對象,只要發生gc,就會被回收。虛引用
:虛引用一般和引用隊列聯合使用,對象若持有虛引用,就等於沒有任何引用,在任何時候都可能被gc,主要用來跟蹤對象被gc的活動。
解決方案
在使用完ThreadLocal
的時候,最後使用remove()
方法進行當前線程變量值的移除。
使用場景
- 線程間數據隔離,每個線程創建自己的ThreadLocal變量副本。
- 進行事務操作,用於存儲線程事務信息。
- 數據庫連接,進行Session會話管理。
- 解決多線程中數據併發不一致的問題。
ThreadLocal和synchronized區別
synchronized
是基於鎖機制,在某一時刻,變量或者代碼只能由一個線程進行訪問,有上鎖和解鎖的邊界,用於解決多個線程之間的數據共享競爭問題。ThreadLocal
是基於每個線程有獨立的變量副本,每個線程在同一時刻都可以訪問變量,可併發訪問,只不過多個線程訪問到的變量不是同一個,是各自線程內獨立的副本,用於解決多個線程需隔離數據共享的問題。
使用方式
代碼示例
public static ThreadLocal<String> local = new ThreadLocal<>();
public static void main(String[] args) {
try {
LongStream.range(100000000, 100000005)
.forEach(a -> new Thread(()-> {
local.set(Thread.currentThread().getName() + "-" + a);
System.out.println("線程名稱:" + Thread.currentThread().getName() + ", local: " + local.get());
}).start());
} finally {
local.remove();
}
}
運行結果
線程名稱:Thread-0, local: Thread-0-100000000
線程名稱:Thread-3, local: Thread-3-100000003
線程名稱:Thread-2, local: Thread-2-100000002
線程名稱:Thread-1, local: Thread-1-100000001
線程名稱:Thread-4, local: Thread-4-100000004
我們可以從運行結果中看出,local是跟隨Thread獨立的。
@Scope多例註解方式
介紹
- 使用
@Scope("prototype")
註解,解決Bean的多例問題,替代性的解決多線程類成員變量共享問題。 - 在使用Spring的IOC功能來管理Bean時,默認是單例的,在多線程下,類的成員變量如果是個可變的值,則會有線程安全問題。需要的時候,我們可以直接拿來即用,使用
@Autowired
或@Resource
註解注入即可。
使用
- Service層使用格式
@Service
@Scope("prototype")
public class XxxService {
}
- 上層注入使用
需要區分上層是否也會是單例。建議使用@Resource
註解注入。