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

后端 未结 6 1740
梦谈多话
梦谈多话 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:40

    Results of a micro benchmark run with jmh

    Benchmark                      Mean     Mean error    Units
    c.a.p.SO18996783.syncOnce      21.003        0.091  nsec/op
    c.a.p.SO18996783.syncTwice     20.937        0.108  nsec/op
    

    => no statistical difference.

    Looking at the generated assembly shows that lock coarsening has been performed and y_sync has been inlined in x_sync although it is synchronized.

    Full results:

    Benchmarks: 
    # Running: com.assylias.performance.SO18996783.syncOnce
    Iteration   1 (5000ms in 1 thread): 21.049 nsec/op
    Iteration   2 (5000ms in 1 thread): 21.052 nsec/op
    Iteration   3 (5000ms in 1 thread): 20.959 nsec/op
    Iteration   4 (5000ms in 1 thread): 20.977 nsec/op
    Iteration   5 (5000ms in 1 thread): 20.977 nsec/op
    
    Run result "syncOnce": 21.003 ±(95%) 0.055 ±(99%) 0.091 nsec/op
    Run statistics "syncOnce": min = 20.959, avg = 21.003, max = 21.052, stdev = 0.044
    Run confidence intervals "syncOnce": 95% [20.948, 21.058], 99% [20.912, 21.094]
    
    Benchmarks: 
    com.assylias.performance.SO18996783.syncTwice
    Iteration   1 (5000ms in 1 thread): 21.006 nsec/op
    Iteration   2 (5000ms in 1 thread): 20.954 nsec/op
    Iteration   3 (5000ms in 1 thread): 20.953 nsec/op
    Iteration   4 (5000ms in 1 thread): 20.869 nsec/op
    Iteration   5 (5000ms in 1 thread): 20.903 nsec/op
    
    Run result "syncTwice": 20.937 ±(95%) 0.065 ±(99%) 0.108 nsec/op
    Run statistics "syncTwice": min = 20.869, avg = 20.937, max = 21.006, stdev = 0.052
    Run confidence intervals "syncTwice": 95% [20.872, 21.002], 99% [20.829, 21.045]
    

提交回复
热议问题