When I see some framework source code like dubbo, I often see code similar to the following:
public class Person {
int age;
String name;
List<Person> persons = new ArrayList<Person>();
public Person findPerson(int lowAge,int highAge){
List<Person> localPersons = persons;
for(Person p : localPersons){
if( p.age >=lowAge && p.age <highAge){
return p;
}
}
return null;
}
}
I just do not understand why not using the member variables persons directly. Local variable localPersons looks redundant to me.
There are two kinds of member variable: instance and static. An instance variable lasts as long as the instance of the class. There will be one copy of it per instance. A static variable lasts as long as the class. There is one copy of it for the entire class. A local variable is declared in a method and only lasts until the method returns:
In C and C++ programming, a Local Variable means it is a variable that can be used inside that function or method or in scope. Local Variables can be only used inside the function or method or a scope that they were declared. They cannot be used in other methods or functions.
Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
A static variable lasts as long as the class. There is one copy of it for the entire class. A local variable is declared in a method and only lasts until the method returns: A local variable is the variable you declare in a function.Its lifespan is on that Function only.
It is possibly a micro-optimization, though I doubt that it would make any difference with a modern JVM. (If that was a worthwhile optimization, the JIT compiler's optimizer will probably do the equivalent transformation at the native code level.)
It is also possibly an (incorrect) attempt to make the code work if there are multiple threads. I say "incorrect" because the programmer is ignoring the requirements of the Java Memory Model. Since there are no clear happens before relationships between two threads accessing the persons
variable or the list that it refers to, threads are liable to see stale data, leading to unpredictable behavior.
There could be other reasons for doing this that are not apparent in your example. (For example, if persons
was declared as volatile
and certain other preconditions were met, this could be thread-safe, and the supposedly redundant local variable could have a valid purpose.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With