简体   繁体   中英

Thread Local - What am I doing wrong?

[IMG] http://i60.tinypic.com/121bww0.jpg[/IMG] (Request to a high rep user, please link the image, it would support the question.)

Hi, The image depicts the web-app flow as I understand it. The browser sends a request to the spring dispatcher servlet. The servlet spawns a new thread per request(I am assuming it does that by default. I don't know how that is controlled.) The code is as following:

public class Result{
    private List<String> response = new ArrayList<String>();
    public setResponse(List<String> list){
        this.response = list;
    }

    public list<String> getResponse(){
        return response ;
    }
}

public class ResponseUtil {
    private static final ThreadLocal<Result> responseObject = new  InheritableThreadLocal<Result>();

    public static void initialize(){
        if(responseObject.get() == null){
            Result result= new Result();
            result.setResponse(new ArrayList<String>());
            responseObject.set(result);
        }
    }

    public static void addMessage(String message){
        List<String> messages = responseObject.get().getResponse();
        messages.add(message);
    }

    public static Response getResponse(){
        return responseObject.get();
    }

}

@Component
public class OnboardingEndPointImpl {

    public Result processOnBoardingFile() {
        ResponseUtil.initialize();
        ResponseUtil.addMessage("a"); 

        return ResponseUtil.getResponse();
    }

}

On sending two rest calls, the output is "a", "a". the string is getting appending to the same list despite it being a thread local.

My understanding is that, each http request(rest call) spawns a new thread. Each call starts by calling the initialize() method. Since each request is a new Thread, the threadLocal must be separate for each http request, but practically I am the threads are writing to the same list. So all the messages are getting added to the same list. This behaviour can only happen if the both the calls are the same thread.

Thanks

Actually, there is a pool of threads serving the requests. The threads get reused for different requests. This is why it is of key importance to unconditionally clear the ThreadLocal when the processing of one request finishes. You should do it using the idiom try {} finally { threadLocal.clear(); } try {} finally { threadLocal.clear(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM