A Pattern that I’ve seen a few times now and still am unsure if it’s correct: I need to invoke some code on the SWT UI thread via Display.syncExec. The code that runs in the UI thread catches a checked exception and wants to propagate this exception to the waiting thread. The pattern looks like this:
SomeCheckedException[] exc = new SomeCheckedException[] { null };
display.syncExec(new Runnable(){
public void run(){
try {
new Work().something();
} catch (SomeCheckedException e){
exc[0] = e;
}
}
});
if (exc[0] != null){
//..
}
Even if there’s no real concurrency here, I still think that this is not really safe in terms of visibility: It could well happen that the UI thread stores an exception, but the invoking thread won’t see this and still read ‘null’ when accessing the array after taking control again. Am I right? Is the best way then just to catch SWTException and check its throwable field via instanceof? EDIT: Hm, that won’t work so easy if it’s a checked exception. I’d need to throw the SWTException from the catch block myself. Better solutions?
Thanks for your help and comments.
This is the sort of case AtomicReference was made for: