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);
}
});
}
dumpS开发者_Go百科tate()
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 using Executors.newCachedThreadPool()
– or the other newXXX()
methods, but that one should be okay for most uses.
That said, I believe this is something you can do with SwingWorker
as well. Just prepare your data in the event handler before you create a SwingWorker
– you're already on the EDT there. If you need to initiate this from a non-EDT thread, prepare the data using SwingUtilities.invokeAndWait()
, and then spin off another thread to do the writing (or do it in the same non-EDT thread you started with.)
SwingWorker
and ExecutorService
provide the same basic service – spin off some work into a background thread without having to manage its lifecycle explicitly. SwingWorker
has a convenient method of communicating with the EDT without using invokeLater()
all over the place that you don't need to use, and ExecutorService
supports 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.
精彩评论