In my client MVC model, the Model object does its busy work in a separate thread because it can potentially take a long time. My question is how to let the gui Controller know that an exception occurred (such as the server being shut down and getting a remote exception) so it can display an appropriate dialog ("connection lost" or "search failed" or whatever). I can't throw it back to the calling method, because the whole point of the worker thread is that the calling method returns immediately so the gui stays responsive. Right now I'm using sort of an error code, where I store a flag that marks an operation as failed, and the controller checks the error code to ensure success. It just seems like checking error codes is an old programming habit. But I thought it would encapsulate the Model a little better if it didn't have to explicitly contact the Controller to say something's wrong. What have other people done in this regard?
Thanks Max, but maybe I wasn't clear on my question: I have a method that runs in a worker thread. Something like:
So the method that creates that new thread has already returned. If doLengthySearch() gets an exception, it has to either store the error in a variable somewhere or explicitly call a method on the gui controller to say there was a problem. It can't throw the exception because there is no one to catch it. So my question was whether this is a common thing in a multi-threaded application, having to store an error flag that marks a task as failed.
My Thread or Runnable classes often look something like this:
It's slightly evolved than an error code - other threads still have to explicitly check getFailureCause() to see if there was an error - but using an Error or Exception object is a convenient Java-friendly way to express what went wrong, without devising a table of different error codes. The waitFor() method is a convenience - depending on how you're having threads communicate you may want to do something else entirely. One way or another though, other threads should probably check for failure before they use the result of whatever this thread was doing.