Home  >  Article  >  Java  >  Detailed explanation of comparative examples of ThreadLocal local threads and synchronization mechanisms in Java

Detailed explanation of comparative examples of ThreadLocal local threads and synchronization mechanisms in Java

黄舟
黄舟Original
2017-03-23 10:28:001847browse

This article mainly introduces relevant information on the comparison of ThreadLocal local threads and synchronization mechanisms in Java. Friends in need can refer to

ThreadLocal design

First look at the interface of ThreadLocal:

Object get() ; // 返回当前线程的线程局部变量副本 protected Object
initialValue(); // 返回该线程局部变量的当前线程的初始值          
void set(Object value); // 设置当前线程的线程局部变量副本的值

ThreadLocal has 3 methods, the most noteworthy of which is initialValue(), which is a protected method, obviously for sub- Class rewriting and implementation. This method returns the initial value of the current thread's local variable in the thread. This method is a delayed calling method that is executed when a thread calls get() or set(Object) for the first time, and is only executed once. The actual implementation in ThreadLocal directly returns a null:

protected Object initialValue() { return null; }

How does ThreadLocal maintain a copy of the variable for each thread? In fact, the implementation idea is very simple. There is a Map in the ThreadLocal class, which is used to store a copy of the variables of each thread.

For example, the following example implementation: It is equivalent to storing a Map. This is the implementation of the get method of ThreadLocal

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();
  }
  
  
   ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
  }

Comparison between ThreadLocal and other synchronization mechanisms

What are the advantages of ThreadLocal compared with other synchronization mechanisms? ThreadLocal and all other synchronization mechanisms are designed to resolve access conflicts to the same variable in multiple threads. In ordinary synchronization mechanisms, object locking is used to achieve safe access to the same variable by multiple threads. At this time, the variable is shared by multiple threads. Using this synchronization mechanism requires a very detailed analysis of when to read and write the variable, when to lock an object, when to release the lock of the object, and so on. All of these are caused by multiple threads sharing resources. ThreadLocal solves the concurrent access of multiple threads from another angle. ThreadLocal will maintain a copy of the variables bound to the thread for each thread, thus isolating the data of multiple threads. Each thread has its own copy of the variables. , so there is no need to synchronize the variable. ThreadLocal provides a thread-safe shared object. When writing multi-threaded code, you can encapsulate the entire unsafe variable into ThreadLocal, or encapsulate the thread-specific state of the object into ThreadLocal.

Since ThreadLocal can hold objects of any type, using ThreadLocal to get the value of the current thread requires forced type conversion. But with the introduction of templates in the new Java version (1.5), the new ThreadLocal8742468051c85b06f0a0af9e3e506b5c class that supports template parameters will benefit from it. It is also possible to reduce forced type conversion and advance some error checking to the compile time, which will simplify the use of ThreadLocal to a certain extent.

Summary

Of course, ThreadLocal cannot replace the synchronization mechanism. The two problem areas are different. The synchronization mechanism is to synchronize multiple threads' concurrent access to the same resources and is an effective way to communicate between multiple threads; ThreadLocal is to isolate the data sharing of multiple threads and is not fundamentally shared between multiple threads. Resources (variables), so of course there is no need to synchronize multiple threads. Therefore, if you need to communicate between multiple threads, use the synchronization mechanism; if you need to isolate sharing conflicts between multiple threads, you can use ThreadLocal, which will greatly simplify your program and make it more readable and concise.

Common uses of ThreadLocal:

Store the current session user
Store some context variables, such as webwork’s ActionContext
Store sessions, such as Spring hibernate orm sessions

Example: Use ThreadLocal to implement per-thread Singleton

Thread local variables are often used to describe stateful "monads" (Singletons) ) or thread-safe shared objects, either by encapsulating unsafe entire variables into a ThreadLocal, or by encapsulating the object's thread-specific state into a ThreadLocal. For example, in an application that has close ties to a database, many of the program's methods may need to access the database. It is inconvenient to include a Connection as a parameter in every method of the system - using a "monad" to access the connection is probably a cruder, but much more convenient technique. However, multiple threads cannot safely share a JDBC Connection. As shown in Listing 3, by using ThreadLocal in a "monad", we can make it easy for any class in our program to obtain a reference to a per-thread Connection. In this way, we can think of ThreadLocal as allowing us to create per-thread monads.

package org.heinrich.app.connection;

import java.sql.Connection;

public class ConnectionUtils {
 
 
 private final static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
 
 
 public Connection getConnection(){
 Connection connection = threadLocal.get();
 if(connection ==null){
  connection = new DBHelper().getConn();
  threadLocal.set(connection);
 }
 
 return connection;
 }
 
 

}

package org.heinrich.app.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//数据库连接
public class DBHelper {
 public static final String url = "jdbc:mysql://localhost:3306/fk_test";
 public static final String name = "com.mysql.jdbc.Driver";
 public static final String user = "root";
 public static final String password = "root";

 public Connection conn = null;

 public Connection getConn() {
 try {
  Class.forName(name);// 指定连接类型
  conn = DriverManager.getConnection(url, user, password);// 获取连接
 } catch (Exception e) {
  e.printStackTrace();
 }
 return conn;
 }

}

A simple way to implement Mysql connection thread safety

Theoretically speaking, ThreadLocal is indeed relative to each thread, and each thread will have its own ThreadLocal. But as mentioned above, general application servers maintain a set of thread pools. Therefore, access by different users may receive the same thread. Therefore, when doing based on TheadLocal, you need to be careful to avoid caching of ThreadLocal variables, causing other threads to access the variables of this thread.

The above is the detailed content of Detailed explanation of comparative examples of ThreadLocal local threads and synchronization mechanisms in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn