2
There was a modification between Java 7 and 8 versions. Where in Java 7 for a local variable to be used within a inner class
should be declared final
. Now compiling with Java 8, this local variable is no longer required to be declared final.
Once the Inner Classes needed to access the local variables, they would have to be copied to another memory region in order to become accessible by it, which could generate multiple copies of the same variable and run the risk of having inconsistent data. What led to this change in Java 8, or all my understanding is wrong?
Java Example 7:
public void msgAsync(final String msg){
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
jText.setText(msg);
}
});
}
Java Example 8:
public void msgAsync(String msg){
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
jText.setText(msg);
}
});
}
Both code snippets compile in their respective versions, but note the use of the modifier final
only used in Java 7.
Related:Why it is not possible to modify local variables when accessed within anonymous classes?
– user28595
@Pauloh.Hartmann even went fast, is that I warn all fds for staff ñ forget.
– Maniero
You can use a lambda instead of an anonymous class in Java 8 to make it simpler:
public void msgAsync(String msg) { java.awt.EventQueue.invokeLater(() -> jText.setText(msg)); }
– Victor Stafusa