Reputation: 1535
Would the following Java code be thread-safe, or does it suffer from possible visibility/safe publication problems?
import java.util.ArrayList;
import java.util.List;
public class WouldThisBeSafe {
public static void main(String[] args) throws InterruptedException {
final List<String> result = new ArrayList<>();
Runnable job = new Runnable() {
@Override
public void run() {
result.add("Hello");
result.add(" ");
result.add("world!");
}
};
Thread t = new Thread(job);
t.start();
t.join();
System.out.println("result = " + result);
}
}
In my real application I have a semi-long running task that needs to load data from a server using multiple remote method calls and must run in the foreground blocking the UI, while reporting progress in a dialog. For this I am using Eclipse/JFace's ProgressMonitorDialog together with an anonymous IRunnableWithProgress instead of Runnable to report the progress. The progress monitor runs the task in a background thread (fork) and shows the progress dialog until the thread is done.
Of course my real question would be whether my actual code with ProgressMonitorDialog and an anonymous IRunnableWithProgress inner class is thread safe, but I suspect that it is equivalent to the simplified example above.
Upvotes: 0
Views: 96
Reputation: 46239
Since you call
t.join();
immediately after
t.start();
the code is perfectly thread-safe. The only issue could have been if you created multiple threads that access result
, or if you had tried to print result
before joining.
Upvotes: 1