spring scope与线程之间的关系怎么解释?有没有什么关联性?
问题如下:
spring scope 模拟为单例模式,则认为多次请求同一个地址时,是按顺序执行,如同时执行 5次 a的test方法,会按顺序执行
如下代码:
@GetMapping("test1")
public Object test1(HttpServletRequest request) throws InterruptedException {
logger.error("this:{},in time:{}", this.toString(), System.currentTimeMillis());
String sleepFlag = request.getParameter("sleep");
if ("on".equalsIgnoreCase(sleepFlag)) {
Thread.currentThread().sleep(10000l);
logger.error("return time:{}", System.currentTimeMillis());
return "sleep 10s";
}
logger.error("return time:{}", System.currentTimeMillis());
return "no sleep";
}
1. http://localhost:8080/test1?sleep=on
2. http://localhost:8080/test1
各执行两次,执行顺序为1-1、1-2、2-1、2-2,打印结果如下:
2018-03-26 16:56:03.793 ERROR 16292 --- [nio-8080-exec-1] c.e.m.web.controller.UserController : this:com.example.multimodule.web.controller.UserController@7f74f276,in time:1522054563793
2018-03-26 16:56:07.349 ERROR 16292 --- [nio-8080-exec-2] c.e.m.web.controller.UserController : this:com.example.multimodule.web.controller.UserController@7f74f276,in time:1522054567349
2018-03-26 16:56:07.349 ERROR 16292 --- [nio-8080-exec-2] c.e.m.web.controller.UserController : return time:1522054567349
2018-03-26 16:56:09.438 ERROR 16292 --- [nio-8080-exec-4] c.e.m.web.controller.UserController : this:com.example.multimodule.web.controller.UserController@7f74f276,in time:1522054569437
2018-03-26 16:56:09.438 ERROR 16292 --- [nio-8080-exec-4] c.e.m.web.controller.UserController : return time:1522054569438
2018-03-26 16:56:13.797 ERROR 16292 --- [nio-8080-exec-1] c.e.m.web.controller.UserController : return time:1522054573797
2018-03-26 16:56:13.801 ERROR 16292 --- [nio-8080-exec-8] c.e.m.web.controller.UserController : this:com.example.multimodule.web.controller.UserController@7f74f276,in time:1522054573801
2018-03-26 16:56:23.801 ERROR 16292 --- [nio-8080-exec-8] c.e.m.web.controller.UserController : return time:1522054583801
结果: 执行过程中 1-1与1-2符合预期结果,即第一次执行完成以后休眠10s执行第二次,但1-1与2-1中间并没有休眠过程(有时间差是因为手工执行的),并且不管controller是否设置为scope=prototype,执行结果都是一样的
求解释
我个人认为是你把单例和线程安全搞混了,单例并不意味着线程安全,多线程同时访问单例同样存在并发问题,除非你手动加锁。下面通过一个例子说明,你觉得最后 count 会是多少?