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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

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

See all articles