一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務器之家 - 編程語言 - Java教程 - Java源碼解析ThreadLocal及使用場景

Java源碼解析ThreadLocal及使用場景

2021-06-28 10:46李燦輝 Java教程

今天小編就為大家分享一篇關于Java源碼解析ThreadLocal及使用場景,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧

threadlocal是在多線程環境下經常使用的一個類。

這個類并不是為了解決多線程間共享變量的問題。舉個例子,在一個電商系統中,用一個long型變量表示某個商品的庫存量,多個線程需要訪問庫存量進行銷售,并減去銷售數量,以更新庫存量。在這個場景中,是不能使用threadlocal類的。

threadlocal適用的場景是,多個線程都需要使用一個變量,但這個變量的值不需要在各個線程間共享,各個線程都只使用自己的這個變量的值。這樣的場景下,可以使用threadlocal。此外,我們使用threadlocal還能解決一個參數過多的問題。例如一個線程內的某個方法f1有10個參數,而f1調用f2時,f2又有10個參數,這么多的參數傳遞十分繁瑣。那么,我們可以使用threadlocal來減少參數的傳遞,用threadlocal定義全局變量,各個線程需要參數時,去全局變量去取就可以了。

接下來我們看一下threadlocal的源碼。首先是類的介紹。如下圖。這個類提供了線程本地變量。這些變量使每個線程都有自己的一份拷貝。threadlocal期望能夠管理一個線程的狀態,例如用戶id或事務id。例如下面的例子產生線程本地的唯一id。線程的id是第一次調用時進行復制,并且在后面的調用中保持不變。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
this class provides thread-local variables.
these variables differ from their normal counterparts in that each thread that accesses
 one (via its get or set method) has its own, independently initialized copy of the variable. threadlocal instances are typically private static fields in classes that
 wish to associate state with a thread (e.g., a user id or transaction id).
for example, the class below generates unique identifiers local to each thread.
 a thread's id is assigned the first time it invokes threadid.get() and
remains unchanged on subsequent calls.
  import java.util.concurrent.atomic.atomicinteger;
  public class threadid {
    // atomic integer containing the next thread id to be assigned
    private static final atomicinteger nextid = new atomicinteger(0);
    // thread local variable containing each thread's id
    private static final threadlocal<integer> threadid =
      new threadlocal<integer>() {
        @override protected integer initialvalue() {
          return nextid.getandincrement();
      }
    };
    // returns the current thread's unique id, assigning it if necessary
    public static int get() {
      return threadid.get();
    }
  }
each thread holds an implicit reference to its copy of a thread-local
variable as long as the thread is alive and the threadlocal instance is
accessible; after a thread goes away, all of its copies of thread-local
 instances are subject to garbage collection (unless other references to
these copies exist).

下面看一下set方法。

set方法的作用是,把線程本地變量的當前線程的拷貝設置為指定的值。大部分子類無需重寫該方法。首先獲取當前線程,然后獲取當前線程的threadlocalmap。如果threadlocalmap不為null,則設置當前線程的值為指定的值,否則調用createmap方法。

獲取線程的threadlocalmap對象,是直接返回的線程的threadlocals,類型為threadlocalmap。也就是說,每個線程都有一個threadlocalmap對象,用于保存該線程關聯的所有的threadlocal類型的變量。threadlocalmap的key是threadlocal,value是該threadlocal對應的值。具體什么意思呢?在程序中,我們可以定義不止一個threadlocal對象,一般會有多個,比如定義3個threadlocal<string>,再定義2個threadlocal<integer>,而每個線程可能都需要訪問全部這些threadlocal的變量,那么,我們用什么數據結構來實現呢?當然,最好的方式就是像源碼中的這樣,每個線程有一個threadlocalmap,key為threadlocal變量名,而value為該線程在該threadlocal變量的值。這個設計實在是太巧妙了。

寫到這里,自己回想起之前換工作面試時,面試官問自己關于threadlocal的實現原理。那個時候,為了準備面試,自己只在網上看了一些面試題,并沒有真正掌握,在回答這個問題時,我有印象,自己回答的是用一個map,線程的id值作為key,變量值作為value,誒,露餡了啊。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * 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();
  threadlocalmap map = getmap(t);
  if (map != null)
    map.set(this, value);
  else
    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);
}

接下來看一下get方法。

源碼如下。首先獲取當前線程的threadlocalmap,然后,從threadlocalmap獲取該threadlocal變量對應的value,然后返回value。如果threadlocalmap為null,則說明該線程還沒有設置該threadlocal變量的值,那么就返回setinitialvalue方法的返回值。其中的initialvalue方法的返回值,通常情況下為null。但是,子類可以重寫initialvalue方法以返回期望的值。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * 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();
  threadlocalmap map = getmap(t);
  if (map != null) {
    threadlocalmap.entry e = map.getentry(this);
    if (e != null) {
      @suppresswarnings("unchecked")
      t result = (t)e.value;
      return result;
    }
  }
  return setinitialvalue();
}
/**
 * variant of set() to establish initialvalue. used instead
 * of set() in case user has overridden the set() method.
 * @return the initial value
 **/
private t setinitialvalue() {
  t value = initialvalue();
  thread t = thread.currentthread();
  threadlocalmap map = getmap(t);
  if (map != null)
    map.set(this, value);
  else
    createmap(t, value);
  return value;
}
protected t initialvalue() {
  return null;
}

文章的最后,簡單介紹一下threadlocalmap這個類,該類是threadlocal的靜態內部類。它對hashmap進行了改造,用于保存各個threadlocal變量和某線程的該變量的值的映射關系。每個線程都有一個threadlocalmap類型的屬性。threadlocalmap中的table數組的長度,與該線程訪問的threadlocal類型變量的個數有關,而與別的無關。

this is the end。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接

原文鏈接:https://blog.csdn.net/li_canhui/article/details/85231116

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲精品在线播放 | 99视频精品国在线视频艾草 | 国产在线91 | 美女毛片在线 | 蘑菇香蕉茄子绿巨人丝瓜草莓 | 嫩草影院国产 | 热久久天天拍天天拍热久久2018 | 亚州中文字幕 | 91麻豆精品激情在线观看最新 | 欧美区一区 | 免费日韩 | 三级黄色图片 | 日本在线一区二区 | 韩国美女被的免费视频 | 狠狠干综合网 | 国产成人综合精品 | 午夜日本大胆裸艺术 | 亚洲午夜久久久久国产 | 91九色最新地址 | 毛片网站免费观看 | 96萝莉| 久久一本岛在免费线观看2020 | 天堂在线免费观看 | 果冻传媒林予曦图片 | 国产亚洲精品高清在线 | 边打电话边操 | 日本大片网 | 亚洲精品高清中文字幕完整版 | 波多野结衣在线中文字幕 | 亚洲天堂2015 | 色吧导航 | 国产一级毛片国语版 | chinese国产打屁股 | 日本在线观看免费观看完整版 | 国产亚洲精品自在线亚洲情侣 | 男人狂躁女人gif动态图 | 免费看美女被靠到爽 | 国产精品怡红院在线观看 | 国产伦精品一区二区三区免 | 好大好爽好涨太深了小喜 | 91频视 |