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 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)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

C language multithreaded programming: a beginner's guide and troubleshooting C language multithreaded programming: a beginner's guide and troubleshooting Apr 04, 2025 am 10:15 AM

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

c What are the differences between the three implementation methods of multithreading c What are the differences between the three implementation methods of multithreading Apr 03, 2025 pm 03:03 PM

Multithreading is an important technology in computer programming and is used to improve program execution efficiency. In the C language, there are many ways to implement multithreading, including thread libraries, POSIX threads, and Windows API.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles