Cancel anonymous SwingWorker thread?

Hello,
A beginner question.
I have a button (A) calling a method, lets call it private void B().
Inside the method B() I have this:
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { do some stuff }
Anyway when I click the A button it calls the method b() and it works fine, the worker thread goes off and does what it needs to do.
If I want to implement a Cancel button to cancel the SwingWorker thread started by private void B(), how should I do it?
Thanks :)

Using SwingWorker is rather neat, and surprisingly studious for a beginner. Make sure that you do non-Swing related work in doInBackground() and Swing-related stuff in done(), that mostly what SwingWorker is for.Yes, that is the way I'm using it together with setProgress to update a progress bar.Great. I hadn't even ever noticed the existence of this method! I learn someting new everyday.
So, you're well ahead of me in terms of using the SwingWorker API! ;)
Your problem is definitely with the Java lanuage, not the SwingWorker.
Instead of using a local variable, make worker an attribute (of the class in which method b() is defined). Then in the action listener for the "Cancel" button, you can invoke the worker's cancel(boolean) method.
I'm not quite sure what you mean exactly when you say an attribute. The method b() is defined within the class that displays the Swing GUI:
public class ResyncWindow extends javax.swing.JFrame { } Do you want me to put the worker outside any methods?Yes, like this:
public class ResyncWindow extends javax.swing.JFrame {
    SwingWorker<Void, Void> worker;
    public ResyncWindow() {
        ... // create launchButton, and wire its actionListener to trigger b()
        ... // create cancelButton, and wire its actionListener to trigger cancel()
    private void b() {
        worker = new SwingWorker<Void,Void>() {
            public void doInBackground() {
                while (!isCancelled() { ..do stuff and set progress... }
        worker.execute();
        cancelButton.setEnabled(true);
        launchButton.setEnabled(false);
    private void cancel() {
         if (!worker.cancel()) {
             ... // display error
         cancelButton.setEnabled(false);
         launchButton.setEnabled(true);
}

Similar Messages

  • Is SwingWorker Thread Cancellation Cooperative?

    Hello,
    Would appreciate any help in understanding this.  My understanding is that cancellation of a SwingWorker thread is cooperative.  However, that isn't what I'm seeing. 
    I have code below that will stop the SwingWorker thread even though I have no operations that are interruptable.  Note for the test that I have specifically put an infinite loop in doStuff().   When I do the cancellation in the main() routine: worker.cancel(true), I end up in the done() function indicating that doInBackground() exited.  It looks like the thread is being killed even in the absence of an interruptable operation.  Note if I change to worker.cancel(false), I get the same effect.  
    class AWorker extends SwingWorker<String, Object> {
      void doStuff() {'
    System.out.println("Entered doStuff");   
        while (true);
      @Override
      public String doInBackground() {
        //System.out.println("doInBackground started");
        doStuff();
        return "hello";
      @Override
      protected void done() {
        try {
          System.out.println("done() entered");
          String status = get();
          System.out.println("done(): get = " + status);
        } catch (Exception e) {
          System.out.println("done(): Exception: " + e);
    public class InterruptThread {
      public static void main(String[] args) throws Exception {
        AWorker worker = new AWorker();
        worker.execute();
        Thread.sleep(5000);
        worker.cancel(true);

    Hello,
    Would appreciate any help in understanding this.  My understanding is that cancellation of a SwingWorker thread is cooperative.  However, that isn't what I'm seeing. 
    I have code below that will stop the SwingWorker thread even though I have no operations that are interruptable.  Note for the test that I have specifically put an infinite loop in doStuff().   When I do the cancellation in the main() routine: worker.cancel(true), I end up in the done() function indicating that doInBackground() exited.  It looks like the thread is being killed even in the absence of an interruptable operation.  Note if I change to worker.cancel(false), I get the same effect.  
    class AWorker extends SwingWorker<String, Object> {
      void doStuff() {'
    System.out.println("Entered doStuff");   
        while (true);
      @Override
      public String doInBackground() {
        //System.out.println("doInBackground started");
        doStuff();
        return "hello";
      @Override
      protected void done() {
        try {
          System.out.println("done() entered");
          String status = get();
          System.out.println("done(): get = " + status);
        } catch (Exception e) {
          System.out.println("done(): Exception: " + e);
    public class InterruptThread {
      public static void main(String[] args) throws Exception {
        AWorker worker = new AWorker();
        worker.execute();
        Thread.sleep(5000);
        worker.cancel(true);

  • Atomic block of code in SwingWorker thread?

    Hi,
    I am coding a Swing application. It has a SwingWorker thread that can be interrupted by a Progress bar.
    Inside the worker thread, there are a few lines of code (not a method) that should be executed all or none. In another word,
    if the thread runs in the middle of this block, the thread must finish this block. How can this be accomplished? This block of code has nothing to do with database read/write. The reason for the block of code being atomic is that I need to make sure of data consistency. There are no other thread except for
    the main thread(event-dispatch thread) and the worker thread.
    Thanks a lot!
    David

    You need to synchronize your atomic block and the code to interrupt the thread on the same object.

  • Cancelling one SwingWorker and starting another

    Hi,
    I have a SwingWorker that does something in the background. When the user presses a button, I want the old worker to get canceled and I want to start a new one. The old worker should do some clean up/logging and close.
    This is the code in my main dispatcher thread:
    public void keyTyped(KeyEvent e)
         if(_controlThread != null)
              _controlThread.cancel(true);
                    java.util.logging.Logger.getLogger("something").fine("output_here");
         _controlThread = new SwingWorker(...);
         _controlThread.execute();
    }The Swing Worker has
    if(this.isCancelled())
        Logger.getLogger("something").fine("closing");
        return;
    }The problem is that the new Worker never starts. Also I noticed that
    Logger.getLogger("something").fine("output_here");
    never logs, I wonder why that is.
    Anyone know what is going on here?
    Thanks

    While trying to reproduce my problem with SSCCE I found the problem.
    import java.awt.event.*;
    import java.util.concurrent.CancellationException;
    import java.util.concurrent.ExecutionException;
    import java.util.logging.*;
    import javax.swing.JFrame;
    import javax.swing.SwingWorker;
    import java.io.*;
    public class main
          * @param args
         public static void main(String[] args) throws IOException
              main a = new main();
              Manager b = a.new Manager();
         class Manager implements KeyListener
              private ControlThread _controlThread;
              Manager()
                   JFrame frame = new JFrame();
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.setVisible(true);
                   frame.addKeyListener(this);
                   frame.setSize(300,300);
              public void keyTyped(KeyEvent e)
                   if(_controlThread != null)
                        _controlThread.cancel(true);
                        System.out.println("cancelled thread");
                   _controlThread = new ControlThread();
                   _controlThread.execute();
              public void keyPressed(KeyEvent e){}
             public void keyReleased(KeyEvent e){}
         class ControlThread extends SwingWorker<Void, Void>
              public Void doInBackground()
                   System.out.println("I'm running");
                   try
                        //do some stuff
                        Thread.sleep(10000);
                   catch (InterruptedException ex)
                        System.out.println("I got cancelled");
                        return null;
                   System.out.println("I finished");
                   return null;
              public void done()
                   try
                        System.out.println("dd");
                        get();
                        System.out.println("ee");
                   catch(InterruptedException ie)
                        System.out.println(": Canceled in done()");
                   catch(ExecutionException ex)
                        System.out.println("Exception in ControlThread: done");
    }This code will fail with a CancellationException in done(). I never saw this exception because I was using loggers and didn't look at the console output. The solution is to catch the CancellationException in done(). The problem is that it is not-documented that get() can throw a CancellationException, because then eclipse would require me to catch it.
    Thanks for helping petes1234.

  • Workflow is Canceled instantly - System.Threading.ThreadAbortException: Thread was being aborted.

    Hi,
    I am trying to solve some issues and strange behaviour with an important workflow hooked up with an InfoPath 2010 list in SharePoint 2010. Everything worked fine until now.
    One workflow item has ended prematurely with the workflow history messages "An error has occurred in workflowname" followed by some init text message I added, and finally "Could not start workflowname"
    (not sure of the exact translation but something like that). Status is still "On Going" (again not sure of translation).
    The workflows after this has gotten the status "Canceled" with no further error messages. However the first init text I added is visible in their workflow history but no other messages are displayed, neither my custom ones nor
    the built in.
    Please help me out, any hints or pointers to help debug this is very appreciated! I do not have other than "view" access so I will have to tell the IT-department to check logs and perform changes if needed.
    /Jesper Wilfing
    Edit: The IT guys sent me the error message from the log file:
    Workflow Infrastructure       72fq
     Unexpected Start Workflow: System.Threading.ThreadAbortException: Thread was being aborted.

    Hi,
    Thank you for sharing and it will help others who meet the same issue.
    Best regards,
    Victoria
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Victoria Xia
    TechNet Community Support

  • TableModel and SwingWorker Thread

    Hi gurus !!! I've spent a lot of hours googling and looking for an answer to that problem:
    I know that all the operations associated to GUI components should be done in Swing dispatch Thread, BUT imagine you are populating a TableModel from within a SwingWorker class similar to this:
    final SwingWorker worker = new SwingWorker() {
             MyTableModel model = null;
            public Object construct() {
              model.executeQuery("select * from mytable");
              // this code is firing tableChanged Event wich is not
              // running on the EventDispatchThread !!!
            //Runs on the event-dispatching thread.
            public void finished() {
               myTable.setModel(model);
        worker.start(); what's happening into method executeQuery("select * from mytable")? This method runs the query and then fires tableDataChanged event to notify the table for repaint, but as we can see in the example is NOT RUNNING IN the EventDispatchThread!!!
    I would like to 'synchronize' this code without firing the tableDataCChangedEvent in the finished method of SwingWorkerClass.
    Please gurus can you give me some points of view about this problem?
    (Sorry for my poor English !!!)

    You are using the wrong table model! You need to create a new one...
    In the construct()...
    (1) MyTableModel newModel = new MyTableModel();
    (2) newModel.executeQuery("select * from mytable");
    In the finished()...
    myTable.setModel(newModel);

  • Stopping threads made by SwingWorker class

    Hello,
    I have simple question. Does anybody know how to do following. I have one thread SwingWorker and this thread is listening on serverSocket. When connection comes it makes new thread which looks after this connection and SwingWorker listens again. Fine, but now I want to interrupt all so I try call cancel() on SwingWorker. What happens to threads made by this SwingWorker which are still alive? Can I interrupt them somehow if they use Input and OUtput stream. When I call this cancel what will happen to the ServerSocket. Where I have to call ssocket.close()? Catch some exception or how?
    Thank you a lot for answer, I am beginner in working with threads so every help is great.
    Martin

    So nobody knows? :)

  • 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.

  • Waiting for Thread to finish execution

    I have a program which uses a thread to copy files. While they are copying, a ProgressMonitor comes up displaying the current file being copied. After this has completed, my main program needs to be notified and go on with it's own code. Either I get the 'I'm done waiting!' message instantly, or not at all, instead of getting it after the thread completes. How do I do this?
    This is what I currently have
    // CLASS 1 //
    //...other code is here
    myMethod()
    ProgressMonitorDemo pmd = new ProgressMonitorDemo();
    while (!pmd.isDone())
    { wait(); }
    System.out.println( "I'm done waiting!" );
    }//Class 2 //
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.*;
    public class ProgressMonitorDemo extends JPanel
      public final static int ONE_SECOND = 1000;
      private ProgressMonitor progressMonitor;
      private Timer timer;
      private LongTask task;
      public ProgressMonitorDemo()
        task = new LongTask();
        timer = new Timer( ONE_SECOND, new TimerListener() );
        progressMonitor = new ProgressMonitor( this, "Running a Long Task", "", 0, task.getLengthOfTask() );
        progressMonitor.setProgress( 0 );
        progressMonitor.setMillisToDecideToPopup( 2 * ONE_SECOND );
        task.go( );
        timer.start();
      public boolean isDone()
        return task.isDone();
       * The actionPerformed method in this class
       * is called each time the Timer "goes off".
      class TimerListener implements ActionListener
        public void actionPerformed( ActionEvent evt )
          progressMonitor.setProgress( task.getCurrent() );
          String s = task.getMessage();
          if( s != null )
            progressMonitor.setNote( s );
          if( progressMonitor.isCanceled() || task.isDone() )
            progressMonitor.close();
            task.stop();
            Toolkit.getDefaultToolkit().beep();
            timer.stop();
    }// CLASS 3 //
    import javax.swing.*;
    import java.io.*;
    import java.awt.dnd.DnDConstants;
    public class LongTask
      private int lengthOfTask;
      private int current = 0;
      private boolean done = false;
      private boolean canceled = false;
      private String statMessage;
      public LongTask()
        //Compute length of task...
        //In a real program, this would figure out
        //the number of bytes to read or whatever.
        lengthOfTask = 400;
       * Called from ProgressBarDemo to start the task.
      public void go( )
        final SwingWorker worker = new SwingWorker()
          public Object construct()
            current = 0;
            done = false;
            canceled = false;
            statMessage = null;
            return new CopyMove();
        worker.start();
       * Called from ProgressBarDemo to find out how much work needs
       * to be done.
      public int getLengthOfTask()
        return lengthOfTask;
       * Called from ProgressBarDemo to find out how much has been done.
      public int getCurrent()
        return current;
      public void stop()
        canceled = true;
        statMessage = null;
       * Called from ProgressBarDemo to find out if the task has completed.
      public boolean isDone()
        return done;
       * Returns the most recent status message, or null
       * if there is no current status message.
      public String getMessage()
        return statMessage;
       * The actual long running task.  This runs in a SwingWorker thread.
      class CopyMove
        private String currOldLoc, currNewLoc, type;
        CopyMove()
          while( current < lengthOfTask )
            try
              Thread.sleep( 1000 );
              current += Math.random() * 100; //make some progress
              if( current > lengthOfTask )
                current = lengthOfTask;
              statMessage = "Completed " + current + " out of " + lengthOfTask + ".";
            catch( Exception e )
              System.out.println( "<ERROR>: Long Task " + e.toString() );
    }

    I tried this but it froze...
    public void myMethod()
    ProgressMonitorDemo pmd = new ProgressMonitorDemo( );
    synchronized( pmd )
       try
         pmd.wait();  
       catch(Exception e){}
    System.out.println( "I'm done waiting!" );
    }Class 2
    class CopyMove
      private String currOldLoc, currNewLoc, type;
      CopyMove()
        while( current < lengthOfTask )
          try
            Thread.sleep( 1000 );
            current += Math.random() * 100; //make some progress
            if( current > lengthOfTask )
              current = lengthOfTask;
            statMessage = "Completed " + current + " out of " + lengthOfTask + ".";
          catch( Exception e )
            System.out.println( "<ERROR>: Long Task " + e.toString() );
        synchronized(this)
          notifyAll();

  • Threads started by "Community Help"

    The Adobe Community Help pages (http://help.adobe.com/en_US/illustrator/cs/using/index.html) used to have a commenting system that was specific to the help files.
    Since many threads were questions, rather than additions and comments on the help files, it has been replaced by a mechanism that creates a thread in the corresponding product forum.
    The threads, started by "Community Help", are titled as and linked to the community help page where the question or comment originated from, and posts are mirrored between this forum and Community help. Comments can be corrections or additions to the help files, and could be links to tutorials relevant to the help page at hand, posted on third party websites, and should therefore not be treated as spam. To keep concise and pertaining information in the help files, these discussions might be curated more closely by the moderators.
    The advantages are the fact that one can now post images, videos, or links, or use advanced formatting, and the side effect is to draw on the combined expertise of all the forum posters.
    The drawback is that the previous comments disappeared, but most have been saved by the Community Help Administrators.
    This should be a great asset to the community, and there might be a few problems during the transition period.
    For example, a "blank post" might show up which is confusing. The moderators are doing their best to delete these posts while the tech staff seems to have fixed issue.
    If you have questions or remarks about these posts, please use this thread of the Forums Comments: http://forums.adobe.com/message/4172835#4172835
    Thank you for your patience and understanding as this change is implemented.

    Martin_Zich wrote:
    Hello,Hi,
    I have simple question. Does anybody know how to do following. I have one thread SwingWorker and this thread is listening on serverSocket. Swing questions should be asked in the Swing forum.
    When connection comes it makes new thread which looks after this connection and SwingWorker listens again. Fine, but now I want to interrupt all so I try call cancel() on SwingWorker. What happens to treads made by this SwingWorker which are still alive? Nothing
    When I call this cancel what will happen to the ServerSocket. Where I have to call ssocket.close()? Catch some exception or how?An interrupted exception will be raised.
    Kaj

  • SwingWorker bug?

    I've got a program that has a GUI and uses a modem to talk to a remote terminal.
    I want the GUI to be updated of the modem's progress, so all modem calls/exchanges with remote terminal are occuring within a SwingWorker thread.
    The user also has a Cancel button to use to kill the SwingWorkerThread.
    I call the interrupt() function on the swingworker thread, but the thread is still going. Has anyone experienced anything like this? Should I not use SwingWorker?

    interrupt will only interrupt blocking/waiting operations. If you did read the documentation for interrupt you would see that.
    If you are doing heavy calculations or spin-looping an interrupt will not do anything.
    You can add calls to interrupted() if you need to check if your operation has been so.

  • Problem with Threads and "plase wait..."-Window

    Hi everyone,
    I have a problem that I'm not able to solve in any way... I have a time-consuming task (a file decryption) which I execute in a separate thread; I've used the SwingWorker class, like suggested by sun-tutorial, and it works right. The problem is that I have to wait that the decryption have finished before continuing with program-execution. Therefore I would like to display a "please wait"-window while the task runs. I've tryed all the possible ways I know but the problem is always the same: the waitWindow is displayed empty, the bounds are painted but the contents no; it's only painted when the decrypt-task has finished. Please help me, I have no more resources....
    decrypt-file code:
    public class DecryptFile {
      private String cryptedFileNameAndPath;
      private ByteArrayInputStream resultStream = null;
      // need for progress
      private int lengthOfTask;
      private int current = -1;
      private String statMessage;
      public DecryptFile(String encZipFileNameAndPath) {
        cryptedFileNameAndPath = encZipFileNameAndPath;
        //Compute length of task...
        // 0 for indeterminate
        lengthOfTask = 0;
      public ByteArrayInputStream getDecryptedInputStream() {
        return this.resultStream;
       * Called from ProgressBarDemo to start the task.
      public void go() {
        current = -1;
        final SwingWorker worker = new SwingWorker() {
          public Object construct() {
            return new ActualTask();
        worker.start();
       * Called from ProgressBarDemo to find out how much work needs
       * to be done.
      public int getLengthOfTask() {
        return lengthOfTask;
       * Called from ProgressBarDemo to find out how much has been done.
      public int getCurrent() {
        return current;
      public void stop() {
        current = lengthOfTask;
       * Called from ProgressBarDemo to find out if the task has completed.
      public boolean done() {
        if (current >= lengthOfTask)
          return true;
        else
          return false;
      public String getMessage() {
        return statMessage;
       * The actual long running task.  This runs in a SwingWorker thread.
      class ActualTask {
        ActualTask () {
          current = -1;
          statMessage = "";
          resultStream = AIUtil.getInputStreamFromEncZip(cryptedFileNameAndPath); //here the decryption happens
          current = 0;
          statMessage = "";
      }The code that calls decryption and displays waitWindow
          final WaitSplash wS = new WaitSplash("Please wait...");
          final DecryptFile cryptedTemplate = new DecryptFile (this.templateFile);
          cryptedTemplate.go();
          while (! cryptedTemplate.done()) {
            try {
              wait();
            } catch (Exception e) { }
          this.templateInputStream = cryptedTemplate.getDecryptedInputStream();
          wS.close();Thanks, thanks, thanks in advance!
    Edoardo

    Maybe you can try setting the priority of the long-running thread to be lower? so that the UI will be more responsive...

  • Using a variable in two threads...

    i am new to java and have a thread question.
    i am using a GUI and then run a swingworker thread to get updates from a server on a regular basis.
    i realize that if the GUI is updated within the swingworker thread i need to use the invokeLater to put it on the EDT.
    but what if i have a boolean variable declared in the main class that i use within the swingworker thread.
    in other words both the EDT and the swingworker thread might use or set the variable.
    does this variable need to be declared in any special way?
    boolean isOn = false; (how i am declaring)
    so one case would be where the EDT sets the variable true or false and the swingworker thread simply checks the state of the variable.
    if (isOn) (do this);
    else (do that);
    in another case both the EDT and the swingthread check and set the var.
    if (isOn) { Thread.sleep(10);}
    isOn = true;
    isOn = false;
    im new to java so just trying to see if this is ok and if i need to declare isOn as syncronized or something.
    not sure if this will work

    There's no need to use both volatile and
    synchronized. Either declare the variable as volatile
    (*), or use synchronization when reading/writing it.
    (*) At least in theory, I'm not sure this has ever
    been guaranteed to work in practice. In any case,
    volatile is superfluous if you use synchronization.You need to use volatile keyword if do not want that compiler optimizes
    you code in multithread applications.
    For example:
        private boolean isDataChanged;
        void setDataChanged(boolean dataChanged){ isDataChanged = dataChanged; }
        boolean isDataChanged(){ return isDataChanged; }
        void someMethod(){
         isDataChanged = false;
         // some code which does not change isDataChanged variable
         if(isDataChanged){
             // code block 1
         }else{
             // code block 2
        }Compiler can optimize someMethod method to the next code because
    isDataChanged is false in if-else statement:
        void someMethod(){
         isDataChanged = false;
         // some code which does not change isDataChanged variable
         // code block 2
        }But isDataChanged viariable can be changed by another thread
    in multifreads applications so optimization will not be correctly
    because isDataChanged can be true in if-else statement.

  • Event Dispatch Thread Hangs, what is wrong?

    The Event Dispatch Thread Hangs when showing a modal dialog while running a
    SwingWorker Thread.
    I have included my code at the bottom of the page. There are three classes. I have posted a bug report to red hat. But I want to make sure my code is correct.
    My test case just puts the SwingWorker to sleep
    but the problem occurs if I do something real, like connect to a database, etc.
    Also I have tried little different variations of the logic calling
    setVisible(true)/(false) in different places and the same problem occurs.
    It seems to work with Sun JDK, note I am using IcedTea with Fedora Core 8.
    Version-Release number of selected component (if applicable):
    [szakrews@tuxtel ~]$ java -version
    java version "1.7.0"
    IcedTea Runtime Environment (build 1.7.0-b21)
    IcedTea Client VM (build 1.7.0-b21, mixed mode)How reproducible:
    Every couple times.
    javac TestClass2
    java TestClass2eventually it will hang. If it doesn't try again.
    You don't have to wait for the program to finish either.
    The program runs the Dialog 10 times but it never works or fails in the middle, it will either work or fail from the first dialog displayed.
    I have included a thread dump. That is about the most informative information I can get. Neither tracing nor writing a custom ThreadQueue or Drawing Manager to trace events produces any helpful information.
    Actual results:
    The JProccessBar won't move, and the SwingWorker finishes but the done() method is never run. The PROGRAM is not hung however because if I close the dialog then it will continue.
    Expected results:
    The JProccessBar should always move and the SwingWorker should always run the done() method.
    Additional info:
    java thread dump after freeze, taken with kill -s SIGQUIT <pid>
    2008-06-25 12:25:50
    Full thread dump IcedTea Client VM (1.7.0-b21 mixed mode):
    "DestroyJavaVM" prio=10 tid=0x938afc00 nid=0x1419 waiting on condition
    [0x00000000..0x0018a074]
       java.lang.Thread.State: RUNNABLE
    "AWT-EventQueue-0" prio=10 tid=0x938ae400 nid=0x1429 in Object.wait()
    [0x07f96000..0x07f96f04]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96748f80> (a java.awt.EventQueue)
            at java.lang.Object.wait(Object.java:503)
            at java.awt.EventQueue.getNextEvent(EventQueue.java:485)
            - locked <0x96748f80> (a java.awt.EventQueue)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:248)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:195)
            at java.awt.Dialog$1.run(Dialog.java:1073)
            at java.awt.Dialog$3.run(Dialog.java:1127)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Dialog.show(Dialog.java:1125)
            at java.awt.Component.show(Component.java:1456)
            at java.awt.Component.setVisible(Component.java:1408)
            at java.awt.Window.setVisible(Window.java:871)
            at java.awt.Dialog.setVisible(Dialog.java:1012)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:72)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:102)
            at TestClass2.showWait(TestClass2.java:79)
            at TestClass2.createAndShowGUI(TestClass2.java:126)
            at TestClass2.access$0(TestClass2.java:114)
            at TestClass2$3.run(TestClass2.java:138)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:227)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:603)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:276)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:191)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:186)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:178)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:139)
    "AWT-Shutdown" prio=10 tid=0x938ad000 nid=0x1428 in Object.wait()
    [0x03ea7000..0x03ea7f84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96749268> (a java.lang.Object)
            at java.lang.Object.wait(Object.java:503)
            at sun.awt.AWTAutoShutdown.run(AWTAutoShutdown.java:281)
            - locked <0x96749268> (a java.lang.Object)
            at java.lang.Thread.run(Thread.java:675)
    "AWT-XAWT" daemon prio=10 tid=0x938a8400 nid=0x1423 runnable
    [0x02ccc000..0x02ccd104]
       java.lang.Thread.State: RUNNABLE
            at sun.awt.X11.XToolkit.waitForEvents(Native Method)
            at sun.awt.X11.XToolkit.run(XToolkit.java:550)
            at sun.awt.X11.XToolkit.run(XToolkit.java:525)
            at java.lang.Thread.run(Thread.java:675)
    "Java2D Disposer" daemon prio=10 tid=0x93854000 nid=0x1421 in Object.wait()
    [0x07aea000..0x07aead84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at sun.java2d.Disposer.run(Disposer.java:143)
            at java.lang.Thread.run(Thread.java:675)
    "Low Memory Detector" daemon prio=10 tid=0x93c15000 nid=0x141f runnable
    [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "CompilerThread0" daemon prio=10 tid=0x93c13400 nid=0x141e waiting on condition
    [0x00000000..0x03a8a954]
       java.lang.Thread.State: RUNNABLE
    "Signal Dispatcher" daemon prio=10 tid=0x93c11c00 nid=0x141d waiting on
    condition [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "Finalizer" daemon prio=10 tid=0x095e7000 nid=0x141c in Object.wait()
    [0x005d2000..0x005d3004]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:177)
    "Reference Handler" daemon prio=10 tid=0x095e2400 nid=0x141b in Object.wait()
    [0x00581000..0x00582084]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7260> (a java.lang.ref.Reference$Lock)
            at java.lang.Object.wait(Object.java:503)
            at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:134)
            - locked <0x966e7260> (a java.lang.ref.Reference$Lock)
    "VM Thread" prio=10 tid=0x095dec00 nid=0x141a runnable
    "VM Periodic Task Thread" prio=10 tid=0x93c17400 nid=0x1420 waiting on condition
    JNI global references: 836
    Heap
    def new generation   total 960K, used 152K [0x93f40000, 0x94040000, 0x966a0000)
      eden space 896K,   9% used [0x93f40000, 0x93f56148, 0x94020000)
      from space 64K, 100% used [0x94020000, 0x94030000, 0x94030000)
      to   space 64K,   0% used [0x94030000, 0x94030000, 0x94040000)
    tenured generation   total 4096K, used 1088K [0x966a0000, 0x96aa0000, 0xb3f40000)
       the space 4096K,  26% used [0x966a0000, 0x967b01b0, 0x967b0200, 0x96aa0000)
    compacting perm gen  total 12288K, used 9169K [0xb3f40000, 0xb4b40000, 0xb7f40000)
       the space 12288K,  74% used [0xb3f40000, 0xb4834740, 0xb4834800, 0xb4b40000)
    No shared spaces configured.CLASS1:
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.RepaintManager;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    public class TestClass2 extends JFrame implements ActionListener {
            /** Action Command for <code>searchbtn</code> */
            public static final String SEARCH_BTN_ACTION = "search_btn_action";
             * Constructor.
            public TestClass2() {
                    setSize(650, 350);
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    setLocation(screenSize.width / 2 - getSize().width / 2,
                                    screenSize.height / 2 - getSize().height / 2);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    exit();
                    JPanel panel = new JPanel();
                    add(panel);
                    setVisible(true);
            @Override
            public void actionPerformed(ActionEvent e) {
                    if (e.getActionCommand().equals(SEARCH_BTN_ACTION)) {
                            JOptionPane.showMessageDialog(this, "Button Pressed");
            public void showWait() {
                    try {
                            WaitDialog.showWaitDialog(this, "Testing...", new SwingWorkerInterface(){
                                    @Override
                                    public Object workToDo() throws Throwable {
                                            Thread.currentThread().sleep(3000);
                                            return null;
                    } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (ExecutionException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
             * Exits the program.
            public void exit(){
                    System.exit(0);
             * Create the GUI and show it. For thread safety, this method should be
             * invoked from the event-dispatching thread.
             * @throws UnsupportedLookAndFeelException
             * @throws IllegalAccessException
             * @throws InstantiationException
             * @throws ClassNotFoundException
             * @throws NullInstanceVariableException
             * @throws SQLException
            private static void createAndShowGUI() {
                    // set look and feel
                    try{
                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                            // Create instance of the ProductCatalog
                            TestClass2 root = new TestClass2();
                            for(int i = 0; i < 10; i++){
                                    root.showWait();
                    }catch(Exception e){
                            e.printStackTrace();
             * @param args
             *            this program does not use arguments
            public static void main(String[] args) {
                    SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                    createAndShowGUI();
    }CLASS 2:
    import java.awt.Component;
    import java.awt.Frame;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingWorker;
    public class WaitDialog extends JDialog {
            private boolean disposed = false;
            private boolean displayed = false;
            private WorkerThread worker = null;
            WaitDialog(Frame parent, String text, SwingWorkerInterface in){
                    super(parent, true);
                    worker = new WorkerThread(in);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowOpened(WindowEvent e) {
                                    worker.execute();
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    disposeWaitDialog();
                    this.setResizable(false);
                    JLabel message = new JLabel();
                    message.setText(text);
                    JProgressBar pb = new JProgressBar();
                    pb.setIndeterminate(true);
                    // set size and location
                    setSize(200, 100);
                    setLocationRelativeTo(parent);
                    JPanel panel = new JPanel();
                    panel.add(message);
                    panel.add(pb);
                    add(panel);
            public void showWaitDialog(){
                    if(displayed == true){
                            return;
                    if(disposed == true){
                            disposed = false;
                            return;
                    disposed = false;
                    displayed = true;
                    setVisible(true);
            public void disposeWaitDialog(){
                    if(disposed == true){
                            return;
                    if(displayed == true){
                            displayed = false;
                            setVisible(false);
                            return;
                    disposed = true;
                    displayed = false;
            public static Object showWaitDialog(Component parent, String text, SwingWorkerInterface in) throws InterruptedException, ExecutionException {
                    WaitDialog waitDialog = null;
                    if (parent == null) {
                            waitDialog = new WaitDialog(JOptionPane.getRootFrame(), text, in);
                    } else {
                            waitDialog = new WaitDialog(JOptionPane.getFrameForComponent(parent), text, in);
                    while(!waitDialog.worker.isDone()){
                            System.out.println("about to show");
                            waitDialog.showWaitDialog();
                            System.out.println("done showing");
                    waitDialog.dispose();
                    return waitDialog.worker.get();
            class WorkerThread extends SwingWorker<Throwable, Void> {
                    private SwingWorkerInterface in = null;
                    WorkerThread(SwingWorkerInterface in){
                            this.in = in;
                    public Throwable doInBackground(){
                                    try {
                                            System.out.println("about to do work");
                                            in.workToDo();
                                            System.out.println("done work no exception");
                                    } catch (Throwable e) {
                                            System.out.println("done work with exception");
                                            return e;
                                    return null;
                    public void done(){
                                    System.out.println("about to dispose");
                                    disposeWaitDialog();
                                    System.out.println("disposed");
    }CLASS 3:
    public interface SwingWorkerInterface {
            public Object workToDo() throws Throwable;
    }

    There's nothing directly wrong with it, but it will
    prevent other threads acquiring the class lock - but
    that may be what you want.True. Although the typical case for code that looks like this would be to use wait--usually the various threads in question require the same lock, so you have to use wait in order for the waiting thread to give it up and allow the other thread to do its work. Hard to say for sure though what he's doing.
    Also, if loading is all that the other thread does, and you're waiting for that thread to die, use join. But then, if that's the case, and you're only waiting for a single other thread, then you might as well just put it all in one thread, as already indicated.

  • Using SwingWorker more than five times

    Hi there,
    I'm having a problem with the SwingWorker.
    A SwingWorker class is called for loading a large file into the database. After I have loaded five files to the database, the sixth loading isn't working and the GUI isn't responsing anymore. Is there a maximum number of SwingWorker Threads that can be used at a time?
    Everything else works fine, and sometimes I can even load more than five files, if the loadings are long enough after each other.
    Can anybody help?

    Darryl.Burke wrote:
    Could also be a problem arising out of not closing database connections when done with them.
    dbHighly probably--about 5 orphaned connections seems to be where things have gone bonkers for me in various languages in the past--C, C++, VB, C#, Pascal, Basic... argh! The mind dizzies.

Maybe you are looking for

  • SAP Crystal Server 2011 installation problems on VM Ware

    Hello, I have download Crystal Server 2011 and I want to install on an VM Ware with: - Windows Server 2008 R2 64Bit - I am the administrator - 2 Core - 6 GB RAM - MS Visualk C++ 2005 and 2008 is installed The VM-Ware ist started with Version 4.0.2 Pl

  • Is Confirmation Message possible in case of File to IDOC

    Hi Friends, It’s a File (sender) to IDOC (receiver) interface. Once the IDOC is posted correctly in SAP, is it possible to generate a confirmation message back to sender file?  I want to know if there is any way to inform the sender system that the t

  • App to fill PDF Forms?

    Are there any app(s) that allow you to fill in PDF forms and save them and/or print them?

  • Extending functionality of JTextField

    Hello, Just getting going with swing here. I'd like to make a custom JTextField that handles typing differently (for example, allowing entry of numbers only, or refusing to allow more than 3 characters, etc). I've got a good start, but I'm stuck at t

  • FL2.x pre-installation

    Hi I have developed a FL2.x application and tested it on lots of Nokia phones. I am happy with the number of Nokias that have FL2.x pre-installed. My question is about pre-installation of FL2.x on some Sony-Ericssons that I have been researching. Acc