Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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())); 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
371 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...