【问题标题】:Spring Autowiring and thread-safetySpring自动装配和线程安全
【发布时间】:2016-07-17 22:04:19
【问题描述】:

我是 Spring 新手,最近创建了一个测试 RESTful Web 服务应用程序。 我正在遵循 Spring @Autowiring 注入 bean 的方式。下面是我的代码和一个问题:

@Service
public class HelloWorld {       

    @Autowired
    private HelloWorldDaoImpl helloWorldDao;

    public void serviceRequest() {
        helloWorldDao.testDbConnection();
    }

}

@RestController
public class HelloWorldController {

    @Autowired
    private HelloWorld helloWorld;

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test() {
        helloWorld.serviceRequest();
        return "Success";
    }
}

现在我的问题是,当我有两个请求同时进入并且它们都共享相同的服务类变量“helloWorld”时,我们如何确保为请求 1 返回的值不会转到请求 2反之亦然?

当我们使用@Autowired 时,Spring 是否会自动处理此类多线程问题?

【问题讨论】:

    标签: spring thread-safety autowired


    【解决方案1】:

    Spring 并不本质上关注应用程序的线程安全,尤其是因为这发生在完全不同的层上。自动装配(和 Spring 代理)与它无关,它只是一种将依赖组件组装成一个工作整体的机制。

    您的示例也不是一个非常具有代表性的示例,因为您提供的两个 bean 实际上都是不可变的。没有可能被并发请求重用的共享状态。为了说明 Spring 真的不关心您的线程安全,您可以尝试以下代码:

    @Service
    public class FooService {       
        // note: foo is a shared instance variable
        private int foo;
    
        public int getFoo() {
            return foo;
        }
    
        public void setFoo(int foo) {
            this.foo = foo;
        }
    }
    
    @RestController
    public class FooController {
    
        @Autowired
        private FooService fooService;
    
        @RequestMapping(value = "/test")
        public String test() {
            int randomNumber = makeSomeRandomNumber();
            fooService.setFoo(randomNumber);
            int retrievedNumber = fooService.getFoo();
            if (randomNumber != retrievedNumber) {
                return "Error! Foo that was retrieved was not the same as the one that was set";
            }
    
            return "OK";
        }
    }
    

    如果你对这个端点进行压力测试,你保证迟早会收到错误消息 - Spring 不会做任何事情来阻止你在脚下开枪。

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-18
        • 2018-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        • 2018-12-05
        相关资源
        最近更新 更多