What is the usage and principle of ThreadLocal in Java
Usage
Isolate data between threads
Avoid passing parameters for every method in the thread, all methods in the thread You can directly obtain the objects managed in
ThreadLocal
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
Use junit
to test:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
The results are as follows, you can see that variables that are not managed by ThreadLocal
have been Unable to match the correct format.
sync task--10 | 10-2023-04-11
sync task--9 | 9-2023-04-11
normal task2-3 | 2-2023- 04-11
normal task2-5 | 2-2023-04-11
normal task2-10 | 2-2023-04-11
normal task2-6 | 2-2023-04-11
sync task--1 | 1-2023-04-11
normal task2-7 | 2-2023-04-11
normal task2-8 | 2-2023-04-11
normal task2- 9 | 2-2023-04-11
sync task--6 | 6-2023-04-11
sync task--3 | 3-2023-04-11
sync task--2 | 2-2023-04-11
sync task--7 | 7-2023-04-11
sync task--4 | 4-2023-04-11
sync task--8 | 8- 2023-04-11
normal task2-4 | 2-2023-04-11
normal task2-1 | 2-2023-04-11
sync task--5 | 5-2023-04- 11
normal task2-2 | 2-2023-04-11
Implementation principle
The process of obtaining data from ThreadLocal
:
Get the corresponding thread first.
Get the ThreadLocalMap in the thread through
getMap(t)
##ThreadLocalMap is a re-implemented hash table. Implements a hash based on two elements:
- User-defined
ThreadLocal
object, for example:
dateFormatLocal.
Entry
object that encapsulates
value.
map.getEntry(this) method, obtain the corresponding
Entry# in the hash table based on the current threadlocal
object ##If it is the first time to use
, use setInitialValue()
to call the user-overridden initialValue()
method Create a map and initialize it with user-specified values. In this design, when the thread dies, the thread shared variable
will be destroyed. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}</pre><div class="contentsignin">Copy after login</div></div>
Note
The object is a weak reference: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
// k: ThreadLocal, v: value
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}</pre><div class="contentsignin">Copy after login</div></div>
The common usage of weak reference is:
1 |
|
Therefore, in
Entry, k
represents the ThreadLocal
object, which is a weak reference. v represents the value
managed by ThreadLocal
, which is a strong reference. Memory Leak
means that useless objects (objects no longer used) continue to occupy memory or the memory of useless objects cannot be released in time, resulting in memory leakage. The waste of space is called a memory leak. As the garbage collector activity increases and memory usage continues to increase, program performance will gradually decline. In extreme cases, OutOfMemoryError will be triggered, causing the program to crash. Memory leak problems mainly occur in the thread pool, because the threads in the thread pool are continuously executed and new tasks are continuously obtained from the task queue for execution. However, there may be
objects in the task, and the ThreadLocal
of these objects will be saved in the thread's ThreadLocalMap
, so ThreadLocalMap
will become more and more big. But
is passed in by the task (worker). After a task is executed, the corresponding ThreadLocal
object will be destroyed. The relationship in the thread is: Thread -> ThreadLoalMap -> Entry<ThreadLocal, Object>
. ThreadLocal
Because it is a weak reference, it will be destroyed during GC, which will cause Entry<null, Object>
to exist in ThreadLoalMap
.
Since the threads in the thread pool are always running, if
ThreadLoalMap is not cleaned up, then Entry< null, Object>
will always occupy memory. The remove()
method will clear the Entry
of key==null
.
Set
ThreadLocal to static
to avoid passing a thread class into the thread pool multiple times Repeat to create Entry
. For example, there is a user-defined thread <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>public class Test implements Runnable{
private static ThreadLocal<Integer> local = new ThreadLocal<>();
@Override
public void run() {
// do something
}
}</pre><div class="contentsignin">Copy after login</div></div>
that uses the thread pool to handle 10 tasks. Then a
will be saved in the Thread.ThreadLocalMap
of each thread used to process tasks in the thread pool, due to the addition of the static
key Word, all local
variables in Entry
in each thread refer to the same variable. Even if a memory leak occurs at this time, all Test classes will have only one local
object, which will not cause excessive memory usage.
1 2 3 4 5 6 7 8 9 10 |
|
Copy after login
The above is the detailed content of What is the usage and principle of ThreadLocal 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
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Assassin's Creed Shadows: Seashell Riddle Solution
1 weeks ago
By DDD
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Where to find the Crane Control Keycard in Atomfall
1 weeks ago
By DDD
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
CakePHP Tutorial
1369
52
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
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
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.
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.
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.
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
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?
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