Java – stop all AWT / swing threads and monitors and things so that only the main thread is left
I have the following
public static void main(String[] args) { boolean running = true; boolean foo= false; while(running) { doSoMetask(); // might set foo true if(foo) { //This call waits/blocks until gui is done working. fireUpSwingGui(); //does work... foo=false; godModeReleaseGUIandALLResourcesOnlyWantMainThreadLeft(); } } }
I hope godmodereleaseguiandallresourcesonlywantmainthreadleft() will explain everything
Remember that when foo becomes true again inside dosometask(), we may start the GUI again at a later stage
Solution
Look at AWT threading issues, which explains the criteria for exiting AWT applications Some of your concerns are as follows:
A quick sample application to demonstrate
import java.awt.Frame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; public class CloseAWT { private static boolean running = true; private static int response = -1; public static void main(String[] args) { boolean showSwing = true; boolean checkFrames = true; while (running) { if (showSwing) { SwingUtilities.invokelater(new Runnable() { public void run() { response = JOptionPane.showConfirmDialog(null,"Hello World?"); } }); showSwing = false; } else { if (response >= 0 && checkFrames) { SwingUtilities.invokelater(new Runnable() { public void run() { // topFrame.dispose(); Frame[] frames = Frame.getFrames(); System.out.printf("frames.length=%d\n",frames.length); } }); checkFrames = false; } } } } }
To make sure that the behavior is as expected, I run this in jpprofiler When you click Yes to close the confirmation dialog box, the 'awt-eventqueue-0' thread is marked as dead After that, the only threads alive are 'main' and the thread listening for Ctrl break
I strongly recommend using analyzers like jpprofiler, yourkit, Jprobe or one of the free analyzers to ensure that you have correctly released all components and deleted all listeners
One last thought... You might want to consider generating the GUI as a separate process and using some kind of IPC to pass information between your daemon and the GUI Although this incurs additional process and IPC overhead, it allows you to better ensure that the GUI is completely cleaned when it is no longer needed