Re: how to make this code thread safer?
Peter Duniho wrote:
If what you say were true, then you could not even count on the Runnable
instance that you created to be valid during the invoked execution,
since that's something that happened before the call to invokeLater(),
but which wasn't synchronized. The "temp" field itself would be safe,
Correct. The Runnable here is not inherently thread safe, hence the
need for the volatile keyword.
but nothing else in the Runnable instance would be (including, for
example, a v-table as might be used to dispatch the call to run()).
There's nothing in the JLS that describes a need to make *methods* safe
for concurrency, or for the programmer to worry about internal
structures such as a hypothetical v-table. The JVM is guaranteed to
construct a class correctly. The fields used by the programmer must be
made thread safe somehow by the programmer.
Right now you are just makin' stuff up.
Weird side note: I was just reading through the JLS to make sure I had
a couple of things right. You know what else is guaranteed to be
visible and thread safe? Objects referred to by final fields, up to the
point where said objects are assigned to the final field. Thus this
works as good as a volatile:
public class Main {
public static void main( String... args ) {
final MyClass test = new MyClass();
SwingUtilities.invokeLater( new Runnable() {
private final MyClass model = test;
public void run() {
... // ok to use model now...
}
} );
}
}