This article mainly introduces relevant information on the correct usage of ThreadLocal in java. Friends who need it can refer to
The correct usage of ThreadLocal in java
usage One: Create private static ThreadLocalThreaLocal’s JDK documentation states: ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. If we want to associate state (such as user ID, transaction ID) with a thread through a class, then a ThreadLocal instance of private static type is usually defined in this class.
For example, in the following class, the private static ThreadLocal instance (serialNum) maintains a "serial number" for each thread that calls the static SerialNum.get() method of the class, which will return the current The thread's sequence number. (The thread's serial number is assigned the first time SerialNum.get() is called and does not change on subsequent calls.)
public class SerialNum { // The next serial number to be assigned private static int nextSerialNum = 0; private static ThreadLocal serialNum = new ThreadLocal() { protected synchronized Object initialValue() { return new Integer(nextSerialNum++); } }; public static int get() { return ((Integer) (serialNum.get())).intValue(); } }
[Example]
public class ThreadContext { private String userId; private Long transactionId; private static ThreadLocal threadLocal = new ThreadLocal(){ @Override protected ThreadContext initialValue() { return new ThreadContext(); } }; public static ThreadContext get() { return threadLocal.get(); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Long getTransactionId() { return transactionId; } public void setTransactionId(Long transactionId) { this.transactionId = transactionId; } }
Usage 2: Create ThreadLocal in the Util class
This is an extension of the above usage, that is, putting the creation of ThreadLocal in the utility class.
[Example] For example, hibernate tool class:
public class HibernateUtil { private static Log log = LogFactory.getLog(HibernateUtil.class); private static final SessionFactory sessionFactory; //定义SessionFactory static { try { // 通过默认配置文件hibernate.cfg.xml创建SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { log.error("初始化SessionFactory失败!", ex); throw new ExceptionInInitializerError(ex); } } //创建线程局部变量session,用来保存Hibernate的Session public static final ThreadLocal session = new ThreadLocal(); /** * 获取当前线程中的Session * @return Session * @throws HibernateException */ public static Session currentSession() throws HibernateException { Session s = (Session) session.get(); // 如果Session还没有打开,则新开一个Session if (s == null) { s = sessionFactory.openSession(); session.set(s); //将新开的Session保存到线程局部变量中 } return s; } public static void closeSession() throws HibernateException { //获取线程局部变量,并强制转换为Session类型 Session s = (Session) session.get(); session.set(null); if (s != null) s.close(); } }
Usage three: Create ThreadLocal in Runnable
Another usage is To create a ThreadLocal inside a thread class, the basic steps are as follows:
1. In a multi-threaded class (such as the ThreadDemo class), create a ThreadLocal object threadXxx to save the need for isolation between threads The object to be processed is xxx.
2. In the ThreadDemo class, create a method getXxx() to obtain the data to be accessed in isolation. Judge in the method that if the ThreadLocal object is null, you should new() an isolated access type. object and cast to the type to be applied.
3. In the run() method of the ThreadDemo class, obtain the data to be operated by calling the getXxx() method. This ensures that each thread corresponds to a data object and can be operated at any time. is this object.
public class ThreadLocalTest implements Runnable{ ThreadLocal<Studen> studenThreadLocal = new ThreadLocal<Studen>(); @Override public void run() { String currentThreadName = Thread.currentThread().getName(); System.out.println(currentThreadName + " is running..."); Random random = new Random(); int age = random.nextInt(100); System.out.println(currentThreadName + " is set age: " + age); Studen studen = getStudent(); //通过这个方法,为每个线程都独立的new一个student对象,每个线程的的student对象都可以设置不同的值 studen.setAge(age); System.out.println(currentThreadName + " is first get age: " + studen.getAge()); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( currentThreadName + " is second get age: " + studen.getAge()); } private Studen getStudent() { Studen studen = studenThreadLocal.get(); if (null == studen) { studen = new Studen(); studenThreadLocal.set(studen); } return studen; } public static void main(String[] args) { ThreadLocalTest t = new ThreadLocalTest(); Thread t1 = new Thread(t,"Thread A"); Thread t2 = new Thread(t,"Thread B"); t1.start(); t2.start(); } } class Studen{ int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
The above is the detailed content of Example code analysis of correctly using ThreadLocal in java. For more information, please follow other related articles on the PHP Chinese website!