SwingWorker lets you prepare some data in a background Thread and then use it in EDT. I am looking for a utility that does the opposite: Prepare data in EDT, and then pass it to a background Thread.
If you’re curious, the use case is saving state of a JTable to disk (column order, size, etc.). I need to talk to its model in EDT, but don’t want to write to disk from this thread.
Something like:
void saveCurrentState(final Table table) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableColumns state = dumpState(table);
saveToDisk(table.getTableKey(), state);
}
});
}
dumpState() needs to run in EDT. saveToDisk() should NOT run in EDT. The whole thing is deliberately wrapped in invokeLater(), and I cannot replace it with invokeAndWait().
You’re probably looking for
ExecutorService. Get one usingExecutors.newCachedThreadPool()– or the othernewXXX()methods, but that one should be okay for most uses.That said, I believe this is something you can do with
SwingWorkeras well. Just prepare your data in the event handler before you create aSwingWorker– you’re already on the EDT there. If you need to initiate this from a non-EDT thread, prepare the data usingSwingUtilities.invokeAndWait(), and then spin off another thread to do the writing (or do it in the same non-EDT thread you started with.)SwingWorkerandExecutorServiceprovide the same basic service – spin off some work into a background thread without having to manage its lifecycle explicitly.SwingWorkerhas a convenient method of communicating with the EDT without usinginvokeLater()all over the place that you don’t need to use, andExecutorServicesupports futures as a more general (non-Swing-specific) way of communicating with asynchronous task. For a fire-and-forget use case as yours both are fine.