Killing a Swing thread

Hello,
How can I kill a Swing thread? For example the program below would never exit. Sure you can type System.exit(0) which would exit anything, but what are the other solutions?
I tried putting chooser = null;
System.gc();in the end of main() but this won’t work.
To formulate my question better - how would I kill a thread I do not have complete command of (i.e. I can’t do usual do/while thread stopping)?
Big thanks in advance.
public class SwingLiveTest{
    public static void main(String[] args) {
        JFileChooser chooser = new JFileChooser();
        if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION) return;
        File file = chooser.getSelectedFile();
        System.out.println(file);
        /*chooser = null;
        System.gc(); */

You can't kill any Thread like this, at least not those where there is no method to call.
It is possible to cause a Thread to stop, call the stop method, however this is not the recommended approach for very good reasons (Read the JavaDocs for java.lang.Thread.stop() method to see why.
It should be possible, once you have obtained a reference to the Thread you wish to stop, to call interrupt() on that Thread.
This is not guaranteed to work because you are dependent on the implementation of the Thread class you are manipulating or the Runnable that the Thread instance is currently running.
There may be classes in the com.sun packages which can aid you with this problem, this is where Sun usually sticks undocumented implementation however these packages are not officially supported and there is no guarantee that classes you use in one VM are available in another, in particular when the VM you are using is not a Sun VM.

Similar Messages

  • How to kill all swing.Timer(s) at end of App

    I am using a javax.swing.Timer to cause text to flash in the text field. However, I noticed that if this timer is running when I stop my app, the timer's thread is still running. It appears that the class that has the timer is not being garbage collected immediately upon application exit. Is there a way to kill all swing timers?
    Thanks,
    John

    No. This is a class whose implementation I was hoping the main application would not have to know about. I was hoping that since I was using swing timers that when the application on which thread the swing timers are executing exited, all the swing timers attached to that application would be stopped.
    Do you have a suggestion how I might be able to do this? I have an application "A" that uses a library class "B" method that happens to start a timer. I do not want "A" to have to explicitly stop "B" when the application is ending. Is there a way I can tag the timer so that it will stop when "A" exits? Or could I somehow link "B" to "A" so that a dispose method on "B" is called when "A" exits or disposes?
    Thanks,
    John

  • In this case, can I modify swing GUI out of swing thread?

    I know the Swing single thread rule and design (Swing is not thread safe).
    For time-consuming task, we are using other thread to do the task and
    we use SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater (or SwingWorker) to update Swing GUI.
    My problem is, my time-consuming task is related to Swing GUI stuff
    (like set expanded state of a huge tree, walk through entire tree... etc), not the classic DB task.
    So my time-consuming Swing task must executed on Swing thread, but it will block the GUI responsivity.
    I solve this problem by show up a modal waiting dialog to ask user to wait and
    also allow user to cancel the task.
    Then I create an other thread (no event-dispatch thread) to do my Swing time-consuming tasks.
    Since the modal dialog (do nothing just allow user to cancel) is a thread spawn by
    Swing event-dispatch thread and block the Swing dispatch-thread until dialog close.
    So my thread can modify Swing GUI stuff safely since there are no any concurrent access problem.
    In this case, I broke the Swing's suggestion, modify Swing stuff out of Swing event-dispatch thread.
    But as I said, there are no concurrent access, so I am safe.
    Am I right? Are you agree? Do you have other better idea?
    Thanks for your help.

    If you drag your modal dialog around in front of the background UI, then there is concurrent access: paint requests in your main window as the foreground window moves around.

  • How can a thread kill another blocked thread?

    Hello All,
    As the title mentioned, lets say i have a main class in which i created a new thread but for some reason, this thread is blocked so i want to find a way to kill this thread from the main class (the interrupt function is not working), is there a workarround to do this?
    Thank you in advance

    Hello,
    First of all, thanks for you interventions, i think i should clearify my case:
    I have a website which has a "Search the site" feature where a user can search the site for specific keywords
    The search engine is an external jar which we use by calling its API, but for some reason this search engine becomes blocked sometimes so my jsp which is calling this API gets also blocked and any subsequent search gets also blocked in the end the number of java threads becomes very high in my system!
    i want to find a way so that if the piece of code calling the search API didnt get excuted during a specific period, i want to kill the thread calling the search API
    lets say the search form is submitted to the following jsp
    // Here we have a SearchThread extends Thread
    /* i launched a new Thread to do the search independatly from the main process*/
    SearchThread task = new SearchThread("search_input");
    task.start();
    /* In the searchThread class we have a run method containing the following line which calls the search API, for some reason , this line never returns and keeps the thread in Running state and so the run() method never returns and so the thread will neve be dead :( */
    SearchLoginSession = new SearchLoginSession (configFile, true);
    Notes:
    1) the stop is deprecated i cant use it
    2) the suspend method will suspend it and not kill it, the thread will remain in memory
    3) the interrupt method didnt work
    4)i am working in a multi-cpu environment
    Finally , what i want is to find a way to remove this thread from memory from the main jsp listed above like
    task.kill() or some workarround
    Thank you for reading and hope you can help me

  • Can a parent thread kill a child thread?

    I'm writing a multi-threaded application in which it is possible for one of the threads to go into an infinite loop. Is there any way for a parent thread to actually kill the child thread that has gone into the infinite loop? Of course the parent thread won't actually be able to discern whether or not the child thread is in an infinite loop. I would specify some time out value, and when it has been exceeded, then I would want to kill the child thread. Is this possible without setting any sort of flag that the child would read, because once it gets stuck inside an infinite loop, there will be no way to read the flag.

    Here's an example of a program that I wrote to simply ping a server. It works somewhat backwards from what you were looking for (the child interrupts the parent) but should provide some clue:
    import java.net.*;
    import java.io.*;
    import java.util.Date;
    public class ServerPing extends Thread {
      String [] args;
      public static void main(String[] args) throws Exception {
        ServerPing sp = new ServerPing(args);
        sp.start();
      ServerPing(String [] args) {
        this.args = args;
      public void run() {
        Pinger pinger = new Pinger(this);
        pinger.start();
        try {
          sleep(30000);
        catch (InterruptedException x) {
          System.exit(0); // this is ok. It means the pinger interrupted.
        System.out.println("TIMEOUT");
        System.exit(1);
    class Pinger extends Thread {
      Thread p = null;
      Pinger (Thread p) {
        this.p = p;
      public void run() {
        try {
          URL simpleURL = new URL("http://localhost:7001/ping.jsp");
          BufferedReader in = new BufferedReader(new InputStreamReader(simpleURL.openStream()));
          String inputLine;
          while ((inputLine = in.readLine()) != null)
          System.out.println(inputLine);
          in.close();
          p.interrupt();   // <<-- interrupt the parent
        catch (Exception x) {
          x.printStackTrace();
    }

  • Can't kill a running thread...

    I'm having some problems killing a thread. Becuase thread.stop() is no longer used, I basically set a flag to tell all the threads to return by checking this flag in the run() method. The problem now is that there is a thread that is getting "stuck" in a class that I have no access to. So basically I assume that its a really long loop, or an infinite loop... either way, that thread doesn't stop even if the "parent" (spawning) thread is "stopped". Any suggestions?
    -L

    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?

  • Swing/Threads, changing the GUI

    Hey all, I have a question related to the java swing class, and manipulating a GUI which is something that I have never done before. Basically I have a threaded Listener class which returns a status boolean. Related to that status, I have a Jlabel which is supposed to display green if the status is true, and red if the status is false, however it is not working correctly. Below is my code, and I would appreciate some help if anyone has a fix, or better way to do this... Thanks in advance
    //Listener Class
    public class Listener extends Thread{
         private boolean isGood = false;
         public Listener(//...) {
         public void run()
              // does stuff here that sets the isGood var
         public bool getIsGood()
              return this.isGood;
    //GUI
    public class Visualizer {
         private static Listener listener;
         public Visualizer(Listener listener){
              this.listener = listener;
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         private static JFrame frame;
         private static JLabel status;
         public static void createAndShowGUI() {
    //Create and set up the window.
    frame = new JFrame("Window");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    status = new JLabel("Listener... ");
    status.setOpaque(true);
    status.setBackground(Color.RED);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    frame.setSize(new Dimension(204, 115));
    frame.setContentPane(status);
    listener.start();
    while(true){
         boolean isGood = listener.getIsGood();
    if(isGood){
    status.setBackground(Color.GREEN);
    else{
    status.setBackground(Color.RED);
         try{
              Thread.sleep(1000);
         }catch(Exception E){
              E.printStackTrace();
    I purposely left out some of the code because I wanted to make it simpler to follow. Essentially this is what is going on, and hopefully someone can point out why its not working and how to fix it. Thank you for reading this.

    thanks for the advice Petes, I was looking for the code tag before but didnt see it. I have created an SSCCE, and I apologize for not making it earlier. Here is the code. The threads seem to be getting stuck, and the label doesnt alternate between red and green as it should. Let me know if you need anything else:
    package simplified;
    public class Main{
         public static void main(String[] args) {
              Listener theListener = new Listener();
              theListener.start();
              Visualizer theView = new Visualizer(theListener);
    //Listener Class
    public class Listener extends Thread{
         private boolean isGood = false;
         public Listener() {
         public void run(){
              if(this.isGood == true){
                   this.isGood = false;
              else{
                   this.isGood = true;
              try{
                   this.sleep(1000);
              }catch(Exception e){
                   e.printStackTrace();
         public boolean getIsGood(){
              return this.isGood;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Dimension;
    public class Visualizer {
         private static Listener listener;
         public Visualizer(Listener listener){
         this.listener = listener;
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                   createAndShowGUI();
         private static JFrame frame;
         private static JLabel status;
         public static void createAndShowGUI() {
              //Create and set up the window.
              frame = new JFrame("Window");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              status = new JLabel("Listener... ");
              status.setOpaque(true);
              status.setBackground(Color.RED);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
              frame.setSize(new Dimension(204, 115));
              frame.setContentPane(status);
              while(true){
                   boolean isGood = listener.getIsGood();
                   if(isGood){
                        status.setBackground(Color.GREEN);
                   else{
                        status.setBackground(Color.RED);
                   try{
                        Thread.sleep(1000);
                   }catch(Exception E){
                        E.printStackTrace();
    }

  • Swing Threads

    Does anybody know how the threads in a swing application are organized. I noticed, that when i start a swing application more then 10 threads are created. Furthermore, when the "main" thread is terminated after showing the main window (a JFrame window), two windows are displayed. When the main-thread is ran in a loop (while (true) {try{Thread.sleep(100);}catch(Exception x){}), only one window is displayed. So, even if the main thread does nothing, it's necessary.
    Furthermore, i realized that, when starting other threads out from the main thread, on some win 2000 systems the threads are properly terminated but the associated handles are not freed - this leads to a "handle leak" after a certain time (48 hours). If the threads are started with invokeLater out from the main thread, then the handles are freed properly when the thread terminates.
    Does anybody know how these facts can be put together to get a bigger whole ?
    Thanks a lot.
    Stephan Gloor
    Switzerland

    hi,
    the rule is:
    swing components are not thread-safe except some, and therefore they should only be changed from within the event dispatch thread. this can be accomplished using the methods invokeLater(Runnable) and invokeAndWait(Runnable) in class javax.swing.SwingUtilities.
    best regards, Michael

  • How to stop/kill/interrupt a thread stuck on reflection method invoke

    Hi all,
    I have a thread that loads some class using reflection and invokes a method in it.
    I want to be able to stop that thread if needed by the user.
    For some reason, interrupt on that thread doesn't do anything - thread is still inside the invoke call.
    Is there any way to stop it?

    The only really safe way to have isolated code is to a seperate process you can kill.
    I wouldn't suggest using Thread.stop unless you have to, but that may be the case here. Stopping the thread this way might be worse than just discarding the Thread and moving on. (depending on what it is doing) i.e. another option is to ignore the thread and hope it doesn't matter. ;)
    However, before you do that I suggest you call Thread.getStackTrace() and log it. This can be useful in diagnosing WHY your thread needed to be kill and possibly give you a chance to fix it next time.

  • How does deadlocking happen when not updating UI on swing thread?

    It looks like the 2 objects that cause the deadlock are the RepaintManager and the JComponent.LOCK object...but I can't really find a scenario where this happens in the code.
    Can anybody shed some light on this?

    Basic rule of thumb:
    If you can't guarantee that your code will run on the AWT-Event thread then wrap your calls in a SwingUtilities.invokeLater() call (or its cousin invokeAndWait()).
    Basically this looks like:
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    // put your gui updating code here
    There are two ways to make something thread safe:
    1) Guarantee calls will always come from the same thread
    2) Synchronized shared objects.
    Swing chose choice 1 since choice 2 would be two big of a performance hit. The thread it uses is the AWT-Event thread. The invokeLater call tosses your Runnable object at the end of the Event Queue. The AWT-Event thread pops a Runnable off the Event Queue processes it and then repeats.
    As to specifically whats happening, I can't say without more information. Really you should go back and make sure all your Swing calls are on the AWT-Event thread. That should solve your current problem and prevent future problems.

  • Swing Thread handling

    Dear all,
    The question is as the follow:
    Condition
    Class A purpose: Get Data from SQL server 2000 e.g.
    SQLDB transaction = new SQLDB();
    transaction.getData();
    Now, I would like to handle the transaction time in order to show that it is processing with Swing component: JLabel, JButton and JFrame. How to write a swing program? Please help me or give me some reference. Thank you so much for your help!
    Regards,
    kzyo

    If java 6, this is an article which I think will probably help you immensely:
    http://java.sun.com/developer/technicalArticles/javase/swingworker/
    It's all about how to implement SwingWorker, a background threader that can among other things give progress reports to the GUI.
    Message was edited by:
    petes1234

  • How to Kill Specific Execute Threads

    Hi.
    Through our application server, we noticed that there were some memory issues
    where the memory usage would rapidly increase from ~ 15Mb to the max heap size.
    Issuing a few thread dumps, we realized that there was a specific thread that
    was churning. This was b/c someone sent a large request in that generated a lot
    of data.
    Anyways, since we couldn't bounce the weblogic server, we had to wait until the
    request ended. Since we know the specific thread that was assigned to that job,
    is there a way to kill the request associated with a specific execute thread and
    reallocate back to the thread pool? We're running weblogic 6.1sp4. I think the
    executequeueruntime bean just gives me back the current configuration of the all
    the threads in the specific queue, which doesn't help me here.
    Thanks.
    --Selena

    Selena,
    how about get the ExecuteQueueRuntimeMBean and get all the execute
    threads (getExecuteThreads() which returns an array of ExecuteThreads )
    and since you know the thread id that is causing the bottleneck, you
    could kill that thread.
    thanks,
    -satya
    Selena wrote:
    Hi.
    Through our application server, we noticed that there were some memory issues
    where the memory usage would rapidly increase from ~ 15Mb to the max heap size.
    Issuing a few thread dumps, we realized that there was a specific thread that
    was churning. This was b/c someone sent a large request in that generated a lot
    of data.
    Anyways, since we couldn't bounce the weblogic server, we had to wait until the
    request ended. Since we know the specific thread that was assigned to that job,
    is there a way to kill the request associated with a specific execute thread and
    reallocate back to the thread pool? We're running weblogic 6.1sp4. I think the
    executequeueruntime bean just gives me back the current configuration of the all
    the threads in the specific queue, which doesn't help me here.
    Thanks.
    --Selena

  • Wake up, wait, and kill one / many threads

    Hello all.
    I am trying to do something that I originally wanted to do with multicasting, but in the end could not.
    Essentially I want to create a bunch of threads, one for each machine I want to 'ping' (not the actual ping, just some kind of 'are you alive?'). These threads will just sit there and wait upon creation.
    Then when a request comes in I want to:
    1. wake them all up so they all send a 'ping' to their respective server.
    2. retrieve the ip address (or name) of the first thread that replies
    3. kill the rest of the threads (if they haven't already died)
    4. go back to waiting
    I've been surfing Google, Java tutorial and these forums and can't seem to put it all together.
    Many thanks for any help!
    Bob

    Hello again, thanks for all of the responses.
    I feel like a bit of a schmuck, I had no idea J2SE 5.0 had all of this new concurrency stuff. All of these things -- Semaphores, CountDownLatch, etc. -- are new to me. I've been trapped in the web / MVC world too long. I've used threads in the past but only for simple stuff, always trying to avoid all the messy stuff like synchronized blocks, wait(), notify(), etc.
    So I am boning up on all this new stuff now, thanks.
    As for you comment, 'I don't see the point in terminating them if you are going to repeat the exercise.', you're right, I didn't mean kill the threads that didn't reply first, I meant ignore them.
    Basically I have a situation where I'll have something like 60 requests per minute on average. For each request I want to wake up all the threads, send out a ping and send the request to the ip address of the first thread that replies.
    The problem of course is that during that one request I may have another, and another, since a ping could take anywhere from less than a second to 5 seconds to timeout. So, for example, If another request comes in while 3 out of the total of 5 threads are still pinging, only 2 will be woken up to send out another ping, and so on.
    It's complicated and it would be a lot easier with a simple multicast message using JGroups or a simple Java multicasting. But alas since these servers that I'll be pinging aren't ours, I can neither install a small multicast listener program on them or even be sure multicasting (port 124.0.0.1) is enabled.
    So that's the deal. I'm going to keep reading. Thanks for all of your help!
    Bob

  • Killing an anonymous Thread

    Hi,
    The question is: How can we kill a Thread that we don't have any reference to it.
    I have a "closed" jar which launches two threads that don't die after the function execution. I cannot kill the JVM by invoking System.exit[0].
    Is there any possibility to access the Threads that are running in memory and kill them? If so how?

    Hi ChuckBing,
    Thanks for replying. Well, actually I think you missunderstood the problem. Let me give you an exemple:
    public class Test {
         public static void main(String[] args) {
              (new DontKillThisAnonymousThread()).start();
              (new KillMeThreadLauncherThread()).start();
    class DontKillThisAnonymousThread extends Thread{
         public void run(){
              try{
                   while(true){
                        System.out.println("I want to live forever...");
                        //From this single line of execution
                        //how can I find another thread (an anonymous one) and kill it.
                        sleep(1000);
              }catch(InterruptedException e){
                   e.printStackTrace();
    class KillMeThreadLauncherThread extends Thread{
         public void run(){
              (new KILL_ME_AnonymousThread()).start();
    class KILL_ME_AnonymousThread extends Thread{
         public void run(){
              try{
                   while(true){
                        System.out.println("Are you able to kill me without killing the JVM...");
                        sleep(1000);
              }catch(InterruptedException e){
                   e.printStackTrace();
    }Thanks

  • That old chestnut: Swing Threading - EventQueue

    First of all, I'm sorry if this topic has been done to death already but I really have searched through the forums and tutorials and not found a solution that I can get to work.
    Scenario (the usual):
    - Swing GUI application
    - Button fires off 'IntensiveProcess'
    - Display a 'MessageBox' while 'IntensiveProcess' is running
    Problem:
    MessageBox is not displayed (or is displayed but its contents are not painted - depending on which [incorrect] implementation I try) until IntensiveProcess has finished.
    I have tried all kinds of different ways of accomplishing this but I can't for the life of me get it to work:
    The implementations I have tried involved various combinations of:
    - EventQueue.invokeLater()
    - EventQueue.invokeAndWait()
    - inner and annonymous-inner Runnable classes
    As far as I understand it, the following strategy should work:
    public class MySwingApp extends JFrame
        //create button with Action: DoButtonAction
        private class DoButtonAction extends AbstractAction
            public void actionPerformed(ActionEvent e)
                // ~~~ IMPLEMENTAION 1  ~~~
                EventQueue.invokeLater(new ShowMessageBox());
                EventQueue.invokeLater(new IntensiveProcess());
                // ~~~ IMPLEMENTAION 2 ~~~
                EventQueue.invokeLater(new ShowMessageBox());
                //cannot call invokeAndWait() from Event Dispatcher thread so:
                (new Thread(new Runnable()
                    public void run()
                        EventQueue.invokeAndWait(new IntensiveProcess());
                )).start();
                // ~~~ IMPLEMENTAION 3  ~~~
                EventQueue.invokeLater(new IntensiveProcess());
                //cannot call invokeAndWait() from Event Dispatcher thread so:
                (new Thread(new Runnable()
                    public void run()
                        EventQueue.invokeAndWait(new ShowMessageBox());
                )).start();
                //dispose of message box if user didn't close it
        private class ShowMessageBox implements Runnable
            //display MessageBox...
        private class IntensiveProcess implements Runnable
            //execute intensive process...
    }None of the above 3 implementations yield the correct result.
    Can anyone please point out where I'm going wrong?
    Thanks all.
    John

    I have implemented your suggestion but sadly I am
    getting the same result: the entire GUI hangs until
    IntensiveProcess has completed, and only then is the
    message box displayed.Hmm, with the intenstive process in its own thread (construct() runs in a thread other than EDT) the GUI shouldn't hang like that, I'm not sure why that is. Maybe try invokeAndWait instead. Or, did you try displaying the message box before creating the SwingWorker? Make sure the message box is not modal if you create it before creating SwingWorker.
    I can't grasp why the EventDispatcher thread is
    getting tied up with IntensiveProcess. I thought
    calling EventQueue.invokeLater() (or SwingWorker) is
    supposed allow the executing thread (in my case the
    EventDispatcher thread) to continue. So why is the
    GUI not getting updated and the message box being
    displayed until AFTER IntensiveProcess finishes?As I understand it, invokeLater means stuff this Runnable into the event queue and run it when its turn comes up, while invokeAndWait runs the Runnable immediately. Neither method will wait for another thread to finish like you're expecting, that's what SwingWorker does.
    For some background info, the SwingWorker's construct() method creates a new non-EDT thread, which is where you're supposed to do time-intensive background work, and the code inside the finished() method will be run in the EDT, which is where you're supposed to update Swing components. The major benefit is the happens-before guarantee, construct() will run to completion before finished() is invoked. Maybe you already knew that, but it's important to know so I wanted to make sure.

Maybe you are looking for

  • All day calendar events not being displayed in the notification centre for iphone 5 post ios 7 upgrade. Please help. Is it a bug?

    All day calendar events not being displayed in the notification centre for iphone 5 post ios 7 upgrade. Please help. Is it a bug? With iOS 6, the all day events showed up in the notification centre but it lacks in the upgrade iOS 7.

  • Personal File sharing doesn't work

    I'm trying to transfer files from my G4 to my G5. I've been successful until now. All of a sudden my G4 will not allow me to enable Personal File Sharing. I click the "Start now" button, and nothing. I have also been having start-up and sleep problem

  • How to put a video within a video (not related to opacity!)

    Hi everyone! I ve been all over the internet for an answer but cant find one! This is getting really fustrating. This is my first serious editing project and I want it to be perfect So what I wanna do is make a transition from one clip to another by

  • Insert update

    dear friends, i'm trying to insert some records in my SQL SERVER 2000 db. but the problem with that is, when i retrieve these record then i find that some additional spaces has been appended with the data that i provided. total length of the column v

  • Error calling EBusiness Suite Public API's from SOA

    Hi, I'm doing some proof of concept work with SOA Suite v 10.1.3.10. When I try to call any of the EBiz suite public API's that have user defined types for records and tables passed as parameters I get the following error when the Oracle Application