script running in Java swing must wait for the end of the threads


I have a java swing application that is running scripts using javax.script. The scripts access the swing widgets and simulate user actions, like JButton.doClick(). Some of the widget actions cause one or more Threads (SwingWorker) to start, and I need the script to wait until all the Threads have completed. But the scripts run in the Event Dispatch Thread, so if I do, for example, a CountDownLatch with an await() inside a FutureTask, then submit() and get(), the get() will stop the EDT, and the GUI hangs. No way to have the script wait without stopping the EDT. Any workarounds for this problem?


I faced a similar problem to this in one of my recent projects. The way I got around it was to get the EDT to create (and run) a new anonymous SwingWorker, that then called (and waited for) my threads:

public void methodCalledByEDT() {
    new SwingWorker<Void, Void>() {
        public Void doInBackground() {
            // Execute threads and wait for them here
            // using the method you described above
            return Void;

        public Void done() {
            // Code to execute when threads have finished goes here
            return Void;

This makes sure that the EDT is free to carry on with it's business - it's the anonymous SwingWorker that gets blocked waiting for the threads to finish.