Anonymous classes, final local variables and synchronization
The code snippet below is copied from the famous article Threads and Swing. Can anybody explain me how synchronization in this example works? The array myStrings is modified in the run() method, in EventDispatcherThread and later it is accessed in the worker thread. Isn't it a synchronization problem as the array is not accessed in the synchronized method or block?
void printTextField()throws Exception{
final String[] myStrings =
new String[2];
Runnable getTextFieldText =
new Runnable(){
publicvoid run(){
myStrings[0] =
textField0.getText();
myStrings[1] =
textField1.getText();
}
};
SwingUtilities.invokeAndWait
(getTextFieldText);
System.out.println(myStrings[0]
+" " + myStrings[1]);
}
[1222 byte] By [
-martin-a] at [2007-10-2 20:21:21]

> The code snippet below is copied from the famous
> article Threads and Swing. Can anybody explain me how
> synchronization in this example works?
invokeAndWait will launch the runnable and then wait until it is done before returning. Therefore the array will be updated before this call returns.
> Isn't it a synchronization problem as
> the array is not accessed in the synchronized method
> or block?
Huh? Because of the above, there is no problem of race conditions WRT the array.
> invokeAndWait will launch the runnable and then wait
> until it is done before returning. Therefore the
> array will be updated before this call returns.
You are right, the read of the array is performed after the write. But the Java Memory Model doesn't guarantee when the changes made by a thread would be visible by other thread, unless the access is synchronized. The worker thread doesn't have any synchronization code when accessing the array.
> the Java Memory Model doesn't guarantee when the changes made by a
> thread would be visible by other thread, unless the access is synchronized.
I believe this is referring to concurrent access. In your case, you do not have
concurrent access because invokeAndWait does just that, wait.
If, on the other hand, you had used invokeLater, it is entirely possible that you
would see no value in the array, partial values, or the complete values due to
the lack of synchronization.
JayDSa at 2007-7-13 23:03:51 >
