首页 > 解决方案 > api客户端调用的线程安全

问题描述

让我们考虑以下简化代码:

@Service
public class Runner {
    private Service service;


    public void process(){
        Thread threadA = new Thread("New Thread") {
            public void run(){
                service.process();
                }};

        Thread threadB = new Thread("New Thread") {
            public void run(){
                service.process();
                }};

        threadA.start();
        threadB.start();
    }
}

@Service
public class Service {

    private ApiClient apiClient;

    public void process(){
        ..do something..
        ResponseObject response = apiClient.callSomething();
        ..do something..
    }
}

ApiClient、Serivce 和 Runner 是 Spring 创建的单例 bean,通过构造函数注入。现在让我们说,当 threadA 执行它的工作时, callSomething() 方法得到一点超时,同时 threadB 开始执行它的工作。threadA 和 threadB 都在等待 callSomething() 的返回,然后来自 threadA 执行的响应返回。是否有可能由于此超时,threadA 和 threadB 都将继续响应 threadA 请求?

标签: javaspringmultithreadingconcurrency

解决方案


推荐阅读