测试String的intern()获取的字符串缓冲池对象 能不能作为同步代码块的锁

版权声明:本文注明出处可以转载。 https://blog.csdn.net/lzxomg/article/details/81031640

测试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分别是 123456654321123456):
            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===============.
    */
    }

如果服务器不做集群,这样貌似是没问题的。

猜你喜欢

转载自blog.csdn.net/lzxomg/article/details/81031640