Why are method parameters reassigned to local variables?

后端 未结 2 643
鱼传尺愫
鱼传尺愫 2020-12-10 12:36

While looking through the Java API source code I often see method parameters reassigned to local variables. Why is this ever done?

void foo(Object bar) {
  O         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 12:51

    This is rule of thread safety/better performance. values in HashMap is volatile. If you are assigning variable to local variable it becomes local stack variable which is automatically thread safe. And more, modifying local stack variable doesn't force 'happens-before' so there is no synchronization penalty when using it(as opposed to volatile when each read/write will cost you acquiring/releasing a lock)

提交回复
热议问题