Location>code7788 >text

3 ThreadLocal questions to ask the interviewer in return

Popularity:553 ℃/2024-09-23 09:22:33

ThreadLocal, a Java people can not get around the topic of interviews, I also wonder why those interviewers like to ask this, I do not know if they themselves have not figured out.

Next, I'd like to start by sayingThreadLocal usage and usage scenariosAnd then3 Questions to Ask Your Interviewer in Counterpoint about ThreadLocal

Usage and Scenarios

One sentence summary:ThreadLocalIt is to prepare a "small independent space" for each thread, which allows each thread to have its own independent copy of the variable. It allows each thread to have its own copy of the variable. When multiple threads access the variable concurrently, you don't need to worry about the conflict between variables and avoid the risk of data sharing between multiple threads.

Usage Scenarios

ThreadLocals usage scenario is mainly in multi-threaded environments, being able to provide each thread with a separate copy of the variable. For example:

  • user-context information: For example, in a Web application, each request may be handled by a different thread, and separate user information is maintained for each thread when processing user requests.
  • Database connection management: For example, in a multi-threaded environment, each thread needs its own separate database connection.
  • transaction management: For example, when dealing with transactions, each thread may need to have its own transaction context to ensure thread-safe transaction operations.
  • uplinkFor example, if the same thread passes data between different methods, but doesn't want to use method parameters to do so, you can use ThreadLocal. like the log tracking scenarios that we commonly use, the tracking IDs will exist in ThreadLocal throughout the chain.

Anyway, there are 2 scenes:

  1. In multi-threaded scenarios, each thread needs to manage variables independently of the other.
  2. A scenario where a thread wants to share independent variables across the entire link.

Usage

When using it, remember the 3 core principles:

  • Each thread has a separate copy of the data.
  • The thread internally uses a ThreadLocalMap to hold the data, and the Key is the ThreadLocal object.
  • When you're done using it, remember to call the remove method to prevent memory overflow.

code example

Example of saving variables independently:

public class ThreadLocal4Independent {

    private static ThreadLocal<Integer> threadLocalVar = new ThreadLocal<>();

    public static void main(String[] args) {
        Runnable task = () -> {
            int num = (int) (() * 100);
            (num);
            ("threading:" + ().getName() + "value of:" + ());
            ();
        };

        new Thread(task, "1").start();
        new Thread(task, "2").start();
    }

}

Example of passing parameters:

public class ThreadLocal4DataPass {
    // Use ThreadLocal to store data that needs to be passed between methods
    private static final ThreadLocal<String> threadLocalData = new ThreadLocal<> ();

    public static void main(String[] args) {
        // Set the data in the main thread
        ("ThreadLocal");

        // Call a different method in the main thread
        method1().
        method2().

        // Clear the ThreadLocal variable to prevent memory leaks.
        method1(); method2(); // Clear the ThreadLocal variable to prevent memory leaks.
    }

    private static void method1() {
        // Get the data in method1 and print it.
        String data = ();
        ("The data that method1 gets is: " + data);
    }

    private static void method2() {
        // Get the data and print it in method2
        String data = (); ("Method 2 got the data: " + data); } private static void method2() { // Get data in method2 and print it.
        ("The data that method2 gets is: " + data);
    }
}

After talking about usage scenarios and methods, next ask the interviewer a few questions.

Question 1: Draw a diagram of the relationship between ThreadLocal and Thread

The relationship between ThreadLocal and Thread is illustrated below.

There are 3 things to keep in mind here

  1. The data actually exists in the ThreadLocalMap, which is held by the Thread. See the source code.

  2. ThreadLocalMap uses a K-V structure internally, and the Key is the ThreadLocal object we defined. See the source code.

  3. ThreadLocalMap has a weak reference relationship to ThreadLocal. See source code.

Question 2: Why is the Key in ThreadLocalMap a weak reference?

So why is the Key in ThreadLocalMap using ThreadLocal? Why is it a weak reference again?

This brings us to 3 wonderful points about the very subtle thinking of the designers of the JDK:

  1. If a thread stores multiple kinds of data, there has to be a rule to find them, so let's go by the defined ThreadLocal object.
  2. For the developer, he only needs to use ThreadLocal to save data, no need to relate to the underlying structure. That is to say, it is enough to expose the simple way of using it to the outside world, and hide all the details that don't need to be known by the caller.
  3. In general the life cycle of Thread will be very long, for example, after the Web container is started, a large number of threads will be started and thrown into the thread pool for reuse. So the life cycle of ThreadLocalMap will also be long. However, the existence of ThreadLocal object cycle is not necessarily long, if, ThreadLocalMap Key to ThreadLocal is a strong reference, then the ThreadLocal object will always exist in memory can not be released, will eventually lead to memory overflow, so the use of weak reference.

Question 3: Why does improper use of ThreadLocal cause memory overflow

As you can see from the relationship diagram above, Value's lifecycle follows the Thread's lifecycle, and if it's never handled, it will also experience a memory overflow.

To avoid memory overflow situation, we have to call remove method even after using ThreadLocal so that JVM can reclaim Value.

summarize

ThreadLocal is a powerful tool in concurrent programming that can provide each thread with a separate copy of its variables to avoid thread safety issues. And thisThreadLocalThe value stored can be used throughout the process. Use the points above to prevent memory overflow.

The end of this article! Welcome to pay attention to, add V (ylxiao) exchange, the whole network can be searched (programmers half a cigarette)

Link to original article:/s/Z3x_tw1jks_KYE0ljETp0Q