What is the synchronization cost of calling a synchronized method from a synchronized method?

后端 未结 6 1703
梦谈多话
梦谈多话 2021-01-01 13:56

Is there any difference in performance between this

synchronized void x() {
    y();
}

synchronized void y() {
}

and this

         


        
6条回答
  •  囚心锁ツ
    2021-01-01 14:30

    Why not test it!? I ran a quick benchmark. The benchmark() method is called in a loop for warm-up. This may not be super accurate but it does show some consistent interesting pattern.

    public class Test {
        public static void main(String[] args) {
    
            for (int i = 0; i < 100; i++) {
                System.out.println("+++++++++");
                benchMark();
            }
        }
    
        static void benchMark() {
            Test t = new Test();
            long start = System.nanoTime();
            for (int i = 0; i < 100; i++) {
                t.x();
            }
            System.out.println("Double sync:" + (System.nanoTime() - start) / 1e6);
    
            start = System.nanoTime();
            for (int i = 0; i < 100; i++) {
                t.x1();
            }
            System.out.println("Single sync:" + (System.nanoTime() - start) / 1e6);
        }
        synchronized void x() {
            y();
        }
        synchronized void y() {
        }
        synchronized void x1() {
            y1();
        }
        void y1() {
        }
    }
    

    Results (last 10)

    +++++++++
    Double sync:0.021686
    Single sync:0.017861
    +++++++++
    Double sync:0.021447
    Single sync:0.017929
    +++++++++
    Double sync:0.021608
    Single sync:0.016563
    +++++++++
    Double sync:0.022007
    Single sync:0.017681
    +++++++++
    Double sync:0.021454
    Single sync:0.017684
    +++++++++
    Double sync:0.020821
    Single sync:0.017776
    +++++++++
    Double sync:0.021107
    Single sync:0.017662
    +++++++++
    Double sync:0.020832
    Single sync:0.017982
    +++++++++
    Double sync:0.021001
    Single sync:0.017615
    +++++++++
    Double sync:0.042347
    Single sync:0.023859
    

    Looks like the second variation is indeed slightly faster.

提交回复
热议问题