最近公司在进行Java开发人员的招聘活动,其中有一道面试题是这样的:“请简单描述一下ThreadLocal类的作用。” 结果发现有很多的面试者没有听说过ThreadLocal或者听说过却不知道这个类究竟是用来做什么的。 因此这里写一篇博客来介绍一下ThreadLocal这个类。
2. 共享状态不可变。 假设某条数据被多线程共享,然而该数据是不可变数据,那么它便没有多线程问题。举例来说: Java中的String类型就是不可变的,因此String的共享并不会导致多线程安全问题。
/**
* 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)
return (T)e.value;
}
return setInitialValue();
}
/**
* 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);
}
我们来看一个在Hibernate中使用ThreadLocal的例子:
private static ThreadLocal<Connection> connectionHolder
= new ThreadLoca<Connection>() {
public Connection initialValue() {
return DriverManager.getConnection(DB_URL);
}
};
public static Connection getConnection() {
return ConnectionHolder.get();
}
上面的例子是一个最经典的ThreadLocal使用案例: 在单线程中创建一个单例变量,并在程序启动时初始化该单例变量,从而避免在调用每个方法时都要传递该变量。然而该单例可能并不是线程安全的,因此,当多线程应用程序在没有互相协作的情况下,可以通过将该单例变量保存到ThreadLocal中,以确保每一个线程都拥有属于自己的实例。
在这里,一个更好理解的说法便是:该单例是一个线程内单例,在多线程应用中,每个线程里都有一个该单例。
通过学习ThreadLocal,我们能够对正确的在项目中使用它,同时,也能够帮助我们对多线程编程有一个更深的认识.
深入理解Java并发编程中的ThreadLocal类

本文详细介绍了ThreadLocal类在Java并发编程中的作用、实现原理及使用场景,包括解决多线程共享数据问题的方法,通过实例展示其在实际开发中的应用,并解释了ThreadLocal是否线程安全的概念。
799

被折叠的 条评论
为什么被折叠?



