Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the question of ThreadLocal in Java interview

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to understand the ThreadLocal questions in the Java interview". In the daily operation, I believe many people have doubts about how to understand the ThreadLocal questions in the Java interview. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the questions of "how to understand the ThreadLocal questions in the Java interview"! Next, please follow the editor to study!

Catalogue

Preface

What is ThreadLocal?

ThreadLoalMap

Hash conflict

Memory leak

How to avoid memory leaks

Preface

During the interview, it is also common for interviewers to examine ThreadLocal, so it is necessary to understand it thoroughly.

Some interviewers will ask straight questions:

"do you know ThreadLocal?"

"tell me about your understanding of ThreadLocal."

Of course, some interviewers will slowly lead to this topic, such as asking "how to prevent your variables from being tampered with by other threads in a multi-threaded environment," leaving the initiative to you, and the rest on your own.

So what can ThreadLocal do? before we understand its application scenario, let's take a look at its implementation principle. Only when we know the implementation principle, can we judge whether it is in line with our business scenario.

What is ThreadLocal?

First of all, it is a data structure, a bit like HashMap, you can save "key: value" key-value pairs, but only one ThreadLocal, and the data of each thread does not interfere with each other.

ThreadLocal localName = new ThreadLocal (); localName.set (Zhan Little Wolf); String name = localName.get ()

Initialize a ThreadLocal object localName in thread 1, and save a value accounting for Little Wolf through the set method, while in thread 1 you can get the previously set value through localName.get (), but if you are in thread 2, you will get a null.

Why and how can this be achieved? However, as mentioned before, ThreadLocal ensures that the data of each thread does not interfere with each other.

Look at the source code of the set (T value) and get () methods

Public void set (T value) {Thread t = Thread.currentThread (); ThreadLocalMap map = getMap (t); if (map! = null) map.set (this, value); else createMap (t, value);} 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 ();} ThreadLocalMap getMap (Thread t) {return t.threadLocals;}

You can find that there is a ThreadLocalMap data structure in each thread, and when the set method is executed, its value is stored in the threadLocals variable of the current thread, and when the set method is executed, it is obtained from the threadLocals variable of the current thread.

Therefore, the value of set in thread 1 is invisible to thread 2, and re-set in thread 2 will not affect the value in thread 1, ensuring that threads will not interfere with each other.

So what exactly is the ThreadLoalMap in each thread?

ThreadLoalMap

This article analyzes the source code of 1.7.

From the name, it can be guessed that it is also a data structure similar to HashMap, but in ThreadLocal, the Map interface is not implemented.

In ThreadLoalMap, it is also initializing an Entry array of size 16, and the Entry object is used to hold every key-value key-value pair, but the key here is always a ThreadLocal object, isn't it amazing? through the set method of the ThreadLocal object, the result is that the ThreadLocal object itself is key and put into the ThreadLoalMap.

It should be noted here that ThreadLoalMap's Entry inherits WeakReference, and the big difference from HashMap is that there is no next field in Entry, so there is no linked list.

Hash conflict

If there is no linked list structure, what if there is a hash conflict?

First take a look at the implementation of inserting a key-value into ThreadLoalMap

Private void set (ThreadLocal key, Object value) {Entry [] tab = table; int len = tab.length; int I = key.threadLocalHashCode & (len-1); for (Entry e = tab [I]; e! = null; e = tab [I = nextIndex (I, len)]) {ThreadLocal k = e.get (); if (k = key) {e.value = value; return } if (k = = null) {replaceStaleEntry (key, value, I); return;}} tab [I] = new Entry (key, value); int sz = + + size; if (! cleanSomeSlots (I, sz) & & sz > = threshold) rehash ();}

Each ThreadLocal object has a hash value threadLocalHashCode, and each initialization of a ThreadLocal object increments the hash value by a fixed size 0x61c88647.

During the insertion process, navigate to the location I in the table according to the hash value of the ThreadLocal object, as follows:

1. If the current position is empty, then just initialize an Entry object and place it at position I.

2. Unfortunately, location I already has an Entry object. If the key of this Entry object happens to be the key to be set, reset the value in the Entry.

3. Unfortunately, the Entry object of location I has nothing to do with the key to be set, so you can only find the next empty location

In this way, when you get, you will also locate the location in the table according to the hash value of the ThreadLocal object, and then determine whether the key in the Entry object is consistent with the key of get. If not, determine the next location.

You can find that if the conflict between set and get is serious, the efficiency is very low, because ThreadLoalMap is an attribute of Thread, so even if you control the number of elements set in your own code, you still can't control the behavior of other code.

Memory leak

ThreadLocal can cause memory leaks. Why?

Let's take a look at the implementation of Entry:

Static class Entry extends WeakReference

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report