测试String的intern()获取的字符串缓冲池对象 能不能作为同步代码块的锁
代码块
controller方法:
@RequestMapping("testSynchronized")
public void testSynchronized(String userId) {
String intern = userId.intern();
synchronized (intern) {
logger.debug("---------------{} begin---------------.",intern);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.debug("==============={} over===============.",intern);
}
/*
连发两次一样useId的请求:
http://localhost:8080/medicine/phuser/testSynchronized?userId=123456
http://localhost:8080/medicine/phuser/testSynchronized?userId=123456
执行结果:
2018-07-13 14:48:46 - ---------------123456 begin---------------.
2018-07-13 14:48:56 - ===============123456 over===============.
2018-07-13 14:48:56 - ---------------123456 begin---------------.
2018-07-13 14:49:06 - ===============123456 over===============.
连发三次一请求(userId分别是 123456,654321,123456):
http://localhost:8080/medicine/phuser/testSynchronized?userId=123456
http://localhost:8080/medicine/phuser/testSynchronized?userId=654321
http://localhost:8080/medicine/phuser/testSynchronized?userId=123456
执行结果:
2018-07-13 14:51:05 - ---------------123456 begin---------------.
2018-07-13 14:51:06 - ---------------654321 begin---------------.
2018-07-13 14:51:15 - ===============123456 over===============.
2018-07-13 14:51:15 - ---------------123456 begin---------------.
2018-07-13 14:51:16 - ===============654321 over===============.
2018-07-13 14:51:25 - ===============123456 over===============.
*/
}
如果服务器不做集群,这样貌似是没问题的。