Java併發程式設計:深入剖析ThreadLocal

誰主沉浮oo7發表於2020-09-25

一.對ThreadLocal的理解

  ThreadLocal,很多地方叫做執行緒本地變數,也有些地方叫做執行緒本地儲存,其實意思差不多。可能很多朋友都知道ThreadLocal為變數在每個執行緒中都建立了一個副本,那麼每個執行緒可以訪問自己內部的副本變數。

  這句話從字面上看起來很容易理解,但是真正理解並不是那麼容易。
  我們還是先來看一個例子:

class ConnectionManager {
     
    private static Connection connect = null;
     
    public static Connection openConnection() {
        if(connect == null){
            connect = DriverManager.getConnection();
        }
        return connect;
    }
     
    public static void closeConnection() {
        if(connect!=null)
            connect.close();
    }
}
`
假設有這樣一個資料庫連結管理類,這段程式碼在單執行緒中使用是沒有任何問題的,但是如果在多執行緒中使用呢?很顯然,在多執行緒中使用會存線上程安全問題:第一,這裡面的2個方法都沒有進行同步,很可能在openConnection方法中會多次建立connect;第二,由於connect是共享變數,那麼必然在呼叫connect的地方需要使用到同步來保障執行緒安全,因為很可能一個執行緒在使用connect進行資料庫操作,而另外一個執行緒呼叫closeConnection關閉連結。

  所以出於執行緒安全的考慮,必須將這段程式碼的兩個方法進行同步處理,並且在呼叫connect的地方需要進行同步處理。

  這樣將會大大影響程式執行效率,因為一個執行緒在使用connect進行資料庫操作的時候,其他執行緒只有等待。

  那麼大家來仔細分析一下這個問題,這地方到底需不需要將connect變數進行共享?事實上,是不需要的。假如每個執行緒中都有一個connect變數,各個執行緒之間對connect變數的訪問實際上是沒有依賴關係的,即一個執行緒不需要關心其他執行緒是否對這個connect進行了修改的。

  到這裡,可能會有朋友想到,既然不需要線上程之間共享這個變數,可以直接這樣處理,在每個需要使用資料庫連線的方法中具體使用時才建立資料庫連結,然後在方法呼叫完畢再釋放這個連線。比如下面這樣:
```java
class ConnectionManager {
     
    private  Connection connect = null;
     
    public Connection openConnection() {
        if(connect == null){
            connect = DriverManager.getConnection();
        }
        return connect;
    }
     
    public void closeConnection() {
        if(connect!=null)
            connect.close();
    }
}
 
 
class Dao{
    public void insert() {
        ConnectionManager connectionManager = new ConnectionManager();
        Connection connection = connectionManager.openConnection();
         
        //使用connection進行操作
         
        connectionManager.closeConnection();
    }
}

這樣處理確實也沒有任何問題,由於每次都是在方法內部建立的連線,那麼執行緒之間自然不存線上程安全問題。但是這樣會有一個致命的影響:導致伺服器壓力非常大,並且嚴重影響程式執行效能。由於在方法中需要頻繁地開啟和關閉資料庫連線,這樣不盡嚴重影響程式執行效率,還可能導致伺服器壓力巨大。

  那麼這種情況下使用ThreadLocal是再適合不過的了,因為ThreadLocal在每個執行緒中對該變數會建立一個副本,即每個執行緒內部都會有一個該變數,且線上程內部任何地方都可以使用,執行緒之間互不影響,這樣一來就不存線上程安全問題,也不會嚴重影響程式執行效能。

  但是要注意,雖然ThreadLocal能夠解決上面說的問題,但是由於在每個執行緒中都建立了副本,所以要考慮它對資源的消耗,比如記憶體的佔用會比不使用ThreadLocal要大。

二.深入解析ThreadLocal類

在上面談到了對ThreadLocal的一些理解,那我們下面來看一下具體ThreadLocal是如何實現的。

  先了解一下ThreadLocal類提供的幾個方法:

public T get() { }
public void set(T value) { }
public void remove() { }
protected T initialValue() { }

get()方法是用來獲取ThreadLocal在當前執行緒中儲存的變數副本,set()用來設定當前執行緒中變數的副本,remove()用來移除當前執行緒中變數的副本,initialValue()是一個protected方法,一般是用來在使用時進行重寫的,它是一個延遲載入方法,下面會詳細說明。

  首先我們來看一下ThreadLocal類是如何為每個執行緒建立一個變數的副本的。

  先看下get方法的實現:

第一句是取得當前執行緒,然後通過getMap(t)方法獲取到一個map,map的型別為ThreadLocalMap。然後接著下面獲取到<key,value>鍵值對,注意這裡獲取鍵值對傳進去的是 this,而不是當前執行緒t。

  如果獲取成功,則返回value值。

  如果map為空,則呼叫setInitialValue方法返回value。

  我們上面的每一句來仔細分析:

  首先看一下getMap方法中做了什麼:

可能大家沒有想到的是,在getMap中,是呼叫當期執行緒t,返回當前執行緒t中的一個成員變數threadLocals。

  那麼我們繼續取Thread類中取看一下成員變數threadLocals是什麼:

實際上就是一個ThreadLocalMap,這個型別是ThreadLocal類的一個內部類,我們繼續取看ThreadLocalMap的實現:

可以看到ThreadLocalMap的Entry繼承了WeakReference,並且使用ThreadLocal作為鍵值。

  然後再繼續看setInitialValue方法的具體實現:

很容易瞭解,就是如果map不為空,就設定鍵值對,為空,再建立Map,看一下createMap的實現:

至此,可能大部分朋友已經明白了ThreadLocal是如何為每個執行緒建立變數的副本的:

  首先,在每個執行緒Thread內部有一個ThreadLocal.ThreadLocalMap型別的成員變數threadLocals,這個threadLocals就是用來儲存實際的變數副本的,鍵值為當前ThreadLocal變數,value為變數副本(即T型別的變數)。

  初始時,在Thread裡面,threadLocals為空,當通過ThreadLocal變數呼叫get()方法或者set()方法,就會對Thread類中的threadLocals進行初始化,並且以當前ThreadLocal變數為鍵值,以ThreadLocal要儲存的副本變數為value,存到threadLocals。

  然後在當前執行緒裡面,如果要使用副本變數,就可以通過get方法在threadLocals裡面查詢。

  下面通過一個例子來證明通過ThreadLocal能達到在每個執行緒中建立變數副本的效果:

public class Test {
    ThreadLocal<Long> longLocal = new ThreadLocal<Long>();
    ThreadLocal<String> stringLocal = new ThreadLocal<String>();
 
     
    public void set() {
        longLocal.set(Thread.currentThread().getId());
        stringLocal.set(Thread.currentThread().getName());
    }
     
    public long getLong() {
        return longLocal.get();
    }
     
    public String getString() {
        return stringLocal.get();
    }
     
    public static void main(String[] args) throws InterruptedException {
        final Test test = new Test();
         
         
        test.set();
        System.out.println(test.getLong());
        System.out.println(test.getString());
     
         
        Thread thread1 = new Thread(){
            public void run() {
                test.set();
                System.out.println(test.getLong());
                System.out.println(test.getString());
            };
        };
        thread1.start();
        thread1.join();
         
        System.out.println(test.getLong());
        System.out.println(test.getString());
    }
}

這段程式碼的輸出結果為:

從這段程式碼的輸出結果可以看出,在main執行緒中和thread1執行緒中,longLocal儲存的副本值和stringLocal儲存的副本值都不一樣。最後一次在main執行緒再次列印副本值是為了證明在main執行緒中和thread1執行緒中的副本值確實是不同的。

  總結一下:

  1)實際的通過ThreadLocal建立的副本是儲存在每個執行緒自己的threadLocals中的;

  2)為何threadLocals的型別ThreadLocalMap的鍵值為ThreadLocal物件,因為每個執行緒中可有多個threadLocal變數,就像上面程式碼中的longLocal和stringLocal;

  3)在進行get之前,必須先set,否則會報空指標異常;

   如果想在get之前不需要呼叫set就能正常訪問的話,必須重寫initialValue()方法。

    因為在上面的程式碼分析過程中,我們發現如果沒有先set的話,即在map中查詢不到對應的儲存,則會通過呼叫setInitialValue方法返回i,而在setInitialValue方法中,有一個語句是T value = initialValue(), 而預設情況下,initialValue方法返回的是null。

看下面這個例子:

public class Test {
    ThreadLocal<Long> longLocal = new ThreadLocal<Long>();
    ThreadLocal<String> stringLocal = new ThreadLocal<String>();
 
    public void set() {
        longLocal.set(Thread.currentThread().getId());
        stringLocal.set(Thread.currentThread().getName());
    }
     
    public long getLong() {
        return longLocal.get();
    }
     
    public String getString() {
        return stringLocal.get();
    }
     
    public static void main(String[] args) throws InterruptedException {
        final Test test = new Test();
         
        System.out.println(test.getLong());
        System.out.println(test.getString());
 
        Thread thread1 = new Thread(){
            public void run() {
                test.set();
                System.out.println(test.getLong());
                System.out.println(test.getString());
            };
        };
        thread1.start();
        thread1.join();
         
        System.out.println(test.getLong());
        System.out.println(test.getString());
    }
}

在main執行緒中,沒有先set,直接get的話,執行時會報空指標異常。

  但是如果改成下面這段程式碼,即重寫了initialValue方法:

public class Test {
    ThreadLocal<Long> longLocal = new ThreadLocal<Long>(){
        protected Long initialValue() {
            return Thread.currentThread().getId();
        };
    };
    ThreadLocal<String> stringLocal = new ThreadLocal<String>(){;
        protected String initialValue() {
            return Thread.currentThread().getName();
        };
    };
 
     
    public void set() {
        longLocal.set(Thread.currentThread().getId());
        stringLocal.set(Thread.currentThread().getName());
    }
     
    public long getLong() {
        return longLocal.get();
    }
     
    public String getString() {
        return stringLocal.get();
    }
     
    public static void main(String[] args) throws InterruptedException {
        final Test test = new Test();
 
        test.set();
        System.out.println(test.getLong());
        System.out.println(test.getString());
     
         
        Thread thread1 = new Thread(){
            public void run() {
                test.set();
                System.out.println(test.getLong());
                System.out.println(test.getString());
            };
        };
        thread1.start();
        thread1.join();
         
        System.out.println(test.getLong());
        System.out.println(test.getString());
    }
}

就可以直接不用先set而直接呼叫get了。

三.ThreadLocal的應用場景

最常見的ThreadLocal使用場景為 用來解決 資料庫連線、Session管理等。
如:

private static ThreadLocal<Connection> connectionHolder
= new ThreadLocal<Connection>() {
public Connection initialValue() {
    return DriverManager.getConnection(DB_URL);
}
};
 
public static Connection getConnection() {
return connectionHolder.get();
}
private static final ThreadLocal threadSession = new ThreadLocal();
 
public static Session getSession() throws InfrastructureException {
    Session s = (Session) threadSession.get();
    try {
        if (s == null) {
            s = getSessionFactory().openSession();
            threadSession.set(s);
        }
    } catch (HibernateException ex) {
        throw new InfrastructureException(ex);
    }
    return s;
}

參考

相關文章