In Java, I know that it is possible to do something like this:
public class Greeter {
public void greetEventually() {
final String greeting = "Hello!";
Job j = new Job() {
public void run() {
System.out.println(greeting);
}
};
j.schedule();
}
}
This would execute the anonymous Job
at some point in the future. This works because anonymous classes are allowed to refer to final variables in the enclosing scope.
What I'm not sure about is the following case:
public class Greeter {
private String greeting;
// ... Other methods that might mutate greeting ...
public void greetEventually() {
Job j = new Job() {
public void run() {
System.out.println(greeting);
}
};
j.schedule();
}
}
In this case my anonymous Job
is referring to a non-final field of the enclosing class. When the Job runs, will I see the value of the greeting
field as it was when the Job was created, or as it is when it is executing? I think I know the answer, but I thought it was an interesting question, and at first it left me and a couple of coworkers second-guessing ourselves for a few minutes.