Basic usage of ThreadLocal

problem description

basic usage of ThreadLocal

the environmental background of the problems and what methods you have tried

my brother has a business scenario where, after executing the basic logic, the information of the order is stored in map and then pushed to another platform by http. In
map, there are two fields whose information is the url address and the other party"s interface address (among other information). But in the actual push process, these two fields are only used inside the method and are not included in the transmitted json. I removed it from map by first put and then remove, and then the leader suggested using ThreadLocal to ensure low intrusiveness of the code, but I didn"t see how to actually store multiple variables to use ThreadLocal

all morning.

related codes

/ / Please paste the code text below (do not replace the code with pictures)

    String a_key = data.get("a_key").toString();
    String b_key = data.get("b_key").toString();
    String c_url = data.get("c_url").toString();
    data.remove("a_key");
    data.remove("b_key");
    data.remove("c_url");

what result do you expect? What is the error message actually seen?

use ThreadLocal to store multiple variables. Please analyze it

.
Apr.02,2021

ThreadLocal, is to bind variables to the thread and save a ThreadLocalMap < ThreadLocal, T > in the thread. I see your requirement. If you want to save multiple values, the simplest solution is to maintain a Map, in ThreadLocal and store multiple variables by Map.
ThreadLocal < Map < String, String > threadLocal = ThreadLocal.withInitial (()-> new HashMap < String, String > ());

    threadLocal.get().put("k1", "v1");
    threadLocal.get().put("k2", "v2");
    threadLocal.get().put("k3", "v3");
    
    String v1 = threadLocal.get().get("k1");
    String v2 = threadLocal.get().get("k2");
    String v3 = threadLocal.get().get("k3");
Menu