Home Java javaTutorial 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

Mar 23, 2017 am 10:28 AM

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); // 设置当前线程的线程局部变量副本的值
Copy after login

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; }
Copy after login

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;
  }
Copy after login

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 ThreadLocal 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;
 }

}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Discuss situations where writing platform-specific code in Java might be necessary. Discuss situations where writing platform-specific code in Java might be necessary. Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

How to use type traits in C? How to use type traits in C? Apr 28, 2025 pm 08:18 PM

typetraits are used in C for compile-time type checking and operation, improving code flexibility and type safety. 1) Type judgment is performed through std::is_integral and std::is_floating_point to achieve efficient type checking and output. 2) Use std::is_trivially_copyable to optimize vector copy and select different copy strategies according to the type. 3) Pay attention to compile-time decision-making, type safety, performance optimization and code complexity. Reasonable use of typetraits can greatly improve code quality.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

How to rename a database in MySQL How to rename a database in MySQL Apr 29, 2025 pm 04:00 PM

Renaming a database in MySQL requires indirect methods. The steps are as follows: 1. Create a new database; 2. Use mysqldump to export the old database; 3. Import the data into the new database; 4. Delete the old database.

How to implement singleton pattern in C? How to implement singleton pattern in C? Apr 28, 2025 pm 10:03 PM

Implementing singleton pattern in C can ensure that there is only one instance of the class through static member variables and static member functions. The specific steps include: 1. Use a private constructor and delete the copy constructor and assignment operator to prevent external direct instantiation. 2. Provide a global access point through the static method getInstance to ensure that only one instance is created. 3. For thread safety, double check lock mode can be used. 4. Use smart pointers such as std::shared_ptr to avoid memory leakage. 5. For high-performance requirements, static local variables can be implemented. It should be noted that singleton pattern can lead to abuse of global state, and it is recommended to use it with caution and consider alternatives.

See all articles