开发者

Why are method parameters reassigned to local variables?

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) {
  Object baz = bar;
  //...
}

This is in java.util.HashMap

public Collection<V> values() {
  Collection<V> vs = values; 
  return (vs != null ? vs : (values = new Values()));开发者_StackOverflow 
}


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)


I'd have to look at some real examples, but the only reason I can think to do this is if the original value needs to be preserved for some computation at the end of the method. In this case, declaring one of the "variables" final would make this clear.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜