Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Java source code: Why is this null-handling logic so complicated? [duplicate]

Tags:

java

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())); 
}
like image 627
initialZero Avatar asked Aug 30 '10 15:08

initialZero


1 Answers

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)

like image 150
Petro Semeniuk Avatar answered Nov 11 '22 22:11

Petro Semeniuk