There are many cases where thread A requires a value that must be computed on thread B. (Most commonly, B == EDT.) Consider this example:
String host;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
host = JOptionPane.showInputDialog("Enter host name: ");
}
});
openConnection(host);
Of course, this doesn’t compile, because the anonymous inner class isn’t allowed to write to host. What’s the simplest, cleanest way to get this to work? I’ve included the ways I know of below.
No:
Use a
Future<T>and possiblyCallable<T>and anExecutorService. AFutureis basically an exact programmatic expression of what you want: a promise of a future answer, and the ability to block until the answer is available. Future also automatically wraps and presents for you an entire, complicated farrago of potential concurrency nightmares and complexities into a few clearly defined exceptions. This is a good thing because it forces you to deal with them, when a roll-your-own solution would likely never reveal them except in some aberrant, difficult to diagnose behavior.For your specific case, you can probably build on a SwingWorker which implements
Future. Rather than duplicate, please take a look at this SO question.