服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|

服务器之家 - 编程语言 - JAVA教程 - Java ThreadLocal详解_动力节点Java学院整理

Java ThreadLocal详解_动力节点Java学院整理

2020-11-18 10:45动力节点海子 JAVA教程

ThreadLocal,很多地方叫做线程本地变量,也有些地方叫做线程本地存储,本文会详细的介绍一下,有兴趣的可以了解一下

一.对threadlocal的理解

threadlocal,很多地方叫做线程本地变量,也有些地方叫做线程本地存储,其实意思差不多。可能很多朋友都知道threadlocal为变量在每个线程中都创建了一个副本,那么每个线程可以访问自己内部的副本变量。

这句话从字面上看起来很容易理解,但是真正理解并不是那么容易。

我们还是先来看一个例子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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进行了修改的。

到这里,可能会有朋友想到,既然不需要在线程之间共享这个变量,可以直接这样处理,在每个需要使用数据库连接的方法中具体使用时才创建数据库链接,然后在方法调用完毕再释放这个连接。比如下面这样:

?
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
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类提供的几个方法:

?
1
2
3
4
public t get() { }
public void set(t value) { }
public void remove() { }
protected t initialvalue() { }

get()方法是用来获取threadlocal在当前线程中保存的变量副本,set()用来设置当前线程中变量的副本,remove()用来移除当前线程中变量的副本,initialvalue()是一个protected方法,一般是用来在使用时进行重写的,它是一个延迟加载方法,下面会详细说明。

首先我们来看一下threadlocal类是如何为每个线程创建一个变量的副本的。

先看下get方法的实现:

Java ThreadLocal详解_动力节点Java学院整理

第一句是取得当前线程,然后通过getmap(t)方法获取到一个map,map的类型为threadlocalmap。然后接着下面获取到<key,value>键值对,注意这里获取键值对传进去的是  this,而不是当前线程t

如果获取成功,则返回value值。

如果map为空,则调用setinitialvalue方法返回value。

我们上面的每一句来仔细分析:

首先看一下getmap方法中做了什么:

Java ThreadLocal详解_动力节点Java学院整理

可能大家没有想到的是,在getmap中,是调用当期线程t,返回当前线程t中的一个成员变量threadlocals。

那么我们继续取thread类中取看一下成员变量threadlocals是什么:

Java ThreadLocal详解_动力节点Java学院整理

实际上就是一个threadlocalmap,这个类型是threadlocal类的一个内部类,我们继续取看threadlocalmap的实现:

Java ThreadLocal详解_动力节点Java学院整理

可以看到threadlocalmap的entry继承了weakreference,并且使用threadlocal作为键值。

然后再继续看setinitialvalue方法的具体实现:

Java ThreadLocal详解_动力节点Java学院整理

很容易了解,就是如果map不为空,就设置键值对,为空,再创建map,看一下createmap的实现:

Java ThreadLocal详解_动力节点Java学院整理

至此,可能大部分朋友已经明白了threadlocal是如何为每个线程创建变量的副本的:

首先,在每个线程thread内部有一个threadlocal.threadlocalmap类型的成员变量threadlocals,这个threadlocals就是用来存储实际的变量副本的,键值为当前threadlocal变量,value为变量副本(即t类型的变量)。

初始时,在thread里面,threadlocals为空,当通过threadlocal变量调用get()方法或者set()方法,就会对thread类中的threadlocals进行初始化,并且以当前threadlocal变量为键值,以threadlocal要保存的副本变量为value,存到threadlocals。

然后在当前线程里面,如果要使用副本变量,就可以通过get方法在threadlocals里面查找。

下面通过一个例子来证明通过threadlocal能达到在每个线程中创建变量副本的效果:

?
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
39
40
41
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());
  }
}

这段代码的输出结果为:

Java ThreadLocal详解_动力节点Java学院整理

从这段代码的输出结果可以看出,在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。

Java ThreadLocal详解_动力节点Java学院整理

看下面这个例子:

?
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
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方法:

?
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
39
40
41
42
43
44
45
46
47
48
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管理等。

如:

?
1
2
3
4
5
6
7
8
9
10
private static threadlocal<connection> connectionholder
= new threadlocal<connection>() {
public connection initialvalue() {
  return drivermanager.getconnection(db_url);
}
};
 
public static connection getconnection() {
return connectionholder.get();
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}

延伸 · 阅读

精彩推荐