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);

Similar Messages

  • 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);
    }

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

  • 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);

  • 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();

  • SwingWorker done() is called before doInBackground is finished

    Hi,
    I'm having a problem understanding how the SwingWorker works. According to java docs: "After the doInBackground method is finished the done method is executed" and there is a happens before relationship. But if I run the code below:
       public class A extends SwingWorker<Void, Void>
             protected Void doInBackground() throws InterruptedException
                  String k = "this is a test";
                  String j = k;
                  while(true)
                       for(int i=0; i<1000; i++)
                            j = j + k;
                            j.replaceAll("nothing", "something");
                       System.out.println("going");
             protected void done()
                  try
                       get();
                  catch(InterruptedException ex){System.out.println("interrupted");}
                  catch(CancellationException ex){System.out.println("cancelled");}
                  System.out.println("done");
    }and call cancel(true) while the thread is running the output I get is
    going
    going
    cancelled
    done
    going
    going
    So that means that done() get's fired after I called cancel(), not after doInBackground() is finished.
    This is causing some serious problems in my actual application, as I do some clean up in done(), but doInBackground() keeps going until it hits my Thread.sleep() code.
    Thanks a lot.

    Hello,
    I think I have a workaround to your problem. By the way, I am the one who submitted [bug 6826514|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6826514] in April of 2009.
    My solution takes advantage of firePropertyChange() and related methods in SwingWorker.
    Here I completely refrain from using done() method to detect the end of doInBackground()'s execution.
    Please bear with me the fact that the code is a little bit long.
    /* GoodWorker.java  */
    package solve;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.SwingWorker;
    * @author Sumudu
    public class GoodWorker extends SwingWorker<Void, Void> {
        private MainFrame mainFrame = null;
        private final String prReallyDone = "ReallyDone";
        private void whenReallyDone() {
            mainFrame.afterWorkerFinishes();
            System.out.println("done");
        public GoodWorker(MainFrame mainFrame) {
            this.mainFrame = mainFrame;
            getPropertyChangeSupport().addPropertyChangeListener(prReallyDone,
                new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent e) {
                    if (e.getNewValue().equals(true)) {
                        whenReallyDone();
        protected Void doInBackground() throws Exception {
            String k = "this is a test";
            String j = k;
            while (!isCancelled()) {
                for (int i = 0; i < 1000; i++) {
                    j = j + k;
                    j.replaceAll("nothing", "something");
                System.out.println("going");
            firePropertyChange(prReallyDone, false, true);
            return null;
    // -- The End --
    /* BadWorker.java */
    package solve;
    import javax.swing.SwingWorker;
    public class BadWorker extends SwingWorker<Void, Void> {
        private MainFrame mainFrame = null;
        public BadWorker(MainFrame mainFrame) {
            this.mainFrame = mainFrame;
        protected Void doInBackground() throws Exception {
            String k = "this is a test";
            String j = k;
            while (!isCancelled()) {
                for (int i = 0; i < 1000; i++) {
                    j = j + k;
                    j.replaceAll("nothing", "something");
                System.out.println("going");
            return null;
        @Override
        protected void done() {
            mainFrame.afterWorkerFinishes();
            System.out.println("done");
    // -- The End --
    /* MainFrame.java */
    package solve;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.concurrent.CancellationException;
    import java.util.concurrent.ExecutionException;
    import javax.swing.SwingWorker;
    public class MainFrame extends javax.swing.JFrame {
        private BadWorker badWorker = null;
        private GoodWorker goodWorker = null;
        private boolean useGoodWoker;
        private void initialize() {
            this.setLocationRelativeTo(null);
            btnStop.setEnabled(false);
            useGoodWoker = chkUseGoodWorker.isSelected();
            btnStart.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    chkUseGoodWorker.setEnabled(false);
                    btnStart.setEnabled(false);
                    btnStop.setEnabled(true);
                    useGoodWoker = chkUseGoodWorker.isSelected();
                    System.out.println("Starting SwingWorker...");
                    if (useGoodWoker) {
                        goodWorker = new GoodWorker(MainFrame.this);
                        goodWorker.execute();
                    } else {
                        badWorker = new BadWorker(MainFrame.this);
                        badWorker.execute();
            btnStop.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    SwingWorker worker = (useGoodWoker ? goodWorker : badWorker);
                    if (worker != null && !worker.isDone()) {
                        btnStop.setEnabled(false);
                        worker.cancel(true);
        public void afterWorkerFinishes() {
            SwingWorker worker = (useGoodWoker ? goodWorker : badWorker);
            try {
                worker.get();
            } catch (InterruptedException ie) {
                System.out.println("Got interrupted while waiting in get().");
            } catch (ExecutionException ee) {
                System.out.print("An exception was thrown inside doInBackground(). ");
                Throwable t = ee.getCause();
                System.out.printf("More specifically, %s %n", t.getMessage());
            } catch (CancellationException ce) {
                System.out.println("SwingWorker got cancelled by you.");
            chkUseGoodWorker.setEnabled(true);
            btnStart.setEnabled(true);
        /** Creates new form MainFrame */
        public MainFrame() {
            initComponents();
            initialize();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
        private void initComponents() {
            chkUseGoodWorker = new javax.swing.JCheckBox();
            buttonPanel = new javax.swing.JPanel();
            btnStart = new javax.swing.JButton();
            btnStop = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("SwingWorkers");
            chkUseGoodWorker.setText("Check this to use Good Worker");
            chkUseGoodWorker.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            chkUseGoodWorker.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            chkUseGoodWorker.setMargin(new java.awt.Insets(0, 0, 0, 0));
            getContentPane().add(chkUseGoodWorker, java.awt.BorderLayout.CENTER);
            btnStart.setText("Start");
            buttonPanel.add(btnStart);
            btnStop.setText("Stop");
            buttonPanel.add(btnStop);
            getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH);
            pack();
        }// </editor-fold>//GEN-END:initComponents
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainFrame().setVisible(true);
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JButton btnStart;
        private javax.swing.JButton btnStop;
        private javax.swing.JPanel buttonPanel;
        private javax.swing.JCheckBox chkUseGoodWorker;
        // End of variables declaration//GEN-END:variables
    // -- The End --

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

  • Down Payment invoice to be reversed or cancelled

    While entering the opening balances we have posted a  Down payment invoice twice by mistake. The Journal entries as a result of this are as under:
    1. While the down payment invoice was posted the first time (correct transaction):
                                                             (Value in Local Currency)
    (a) Party A      Dr.                            10,000/-
         To Prepayments rec 3rd                          10,000/-
       (Invoice No.001)
    (b)While booking the payment for the above invoice no.001:
    Bank     Dr.                                       10,000/-
         To Party A                                                              10,000/-
       (Receipt for Invoice No.001)
    2. While the down payment invoice was posted the second time (duplication done by mistake):
                                                             (Value in Local Currency)
    (a) Party A      Dr.                            10,000/-
         To Prepayments received                          10,000/-
       (Invoice No.002)
    (b)To rectify the above invoice no.002 the below Journal was passed:
    Prepayments received    Dr.                     10,000/-
         To Party  A                                                             10,000/-
       (Reversal of Invoice No.002)
    The opening balances were then tallied and we started posting the regular transactions
    However when we made a A/R Invoice for the above party we wanted to call the down payment invoices we got both both down payment invoices 001 and 002. We want to adjust only down payment invoice 001 and want to cancel down payment invoice 002.
    Please advise how to cancel or reverse down payment invoice 002.
    Thanks in advance
    Venkatesan Swaminathan

    Hi Venkatesan,
    please see this thread:
    Cancel down payment
    All the best,
    Kerstin

  • BILLING DOCUMENT CANCELLATION PROBLEMS

    Hi,
    in my process from POS we have created IDOCS,than IDOCS we are creating several docuemtns like,
    1.article document
    2.billing documents,
    Now from billing documents, accounting documents has been created with different g/l account and also with posting key 40,50.
    now when we saw the bill doc document flow,it shows accounting doc as cleared.
    its show entry at G/L level not at customer level,
    now when i want to cancel accounting doc its shows tht this document has not been cancel because it not posted.
    and when from t.code VF11 i am gng to cancel billing document at the time its shows:
    original document is not same as billing document and its contains some error.
    Pls help on this

    Refer following thread
    Cancel / reverse billing document cancellation document?
    All the best.
    Thanks & Regards
    JP

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

  • SwingWorker behaviour on the Mac

    Hi everyone,
    I am fairly new to swing applications and am having a problem.
    I have written an app that fires off a SwingWorker thread and processes some work. The main thread has a Swing timer that fires, reads a ptogress value from the SwingWorker and updates a progressbar. When I run this on a Windows XP client it all behaves as expected. When I run it on a Mac OSX 10.2.8 the Timer event fires once and then the thread runs through and the Timer never fires again. When it did fires once it look as if something goes wrong when it accesses the SwingWorker.
    So it appears that I have a threading issue (only on the mac). The methods I access are synchronized. Is there anything else I should try.
    Thanks
    Pete

    can we have some code sample to look into it

  • Thread concurrency problem - how to know when thread is dead?

    My applet uses a thread to draw an iteration graph step by step.
    The user as the option of pressing two buttons:
    - PLAY button - iteration Points are stored in an arrayList and drawn step by step (a sleeping time follows each step) (drawIterations thread)
    - TO_END button - iteration Points are all stored in the arrayList (swingworker thread) and after all of them have been stored the graph is drawn instantly.
    I have problems in this situation:
    When executing the PLAY-button thread, if the user presses TO_END button, the remaining graph lines should draw instantly. Sometimes I get more points on the graph than I should. It seems that the PLAY thread, which I stop when TO_END buton is pressed, still remains storing new points into the arrayList concurrently to the new thread created after TO_END button was pressed .
    Any ideas?
    I'm already using synchronization.
    private volatile Thread drawIterations;
    public void playButtonClick(JToggleButton btn) {
         pointSet1 = new ArrayList<Point2D.Double>();
         if (drawIterations == null) drawIterations = new Thread(this,   "drawIterations");
         drawIterations.start();
    public void toEndButtonClick(JToggleButton btn) {
         stopThread() ;
         pointSet1 = new ArrayList<Point2D.Double>();
         computeIterationGraphPointsAndRefreshGraph();
    public synchronized void stopThread() {
         drawIterations = null;
         notify();
    private void computeIterationGraphPointsAndRefreshGraphs() {
         SwingWorker worker = new SwingWorker() {
              public Object construct() {
                   // compute all iteration points
                         //repaint graph
         worker.start();
    }Is there a way of testing if a thread is actually dead after setting the thread object to null??

    In general, a Thread keeps running until it's run
    method completes. Threads don't stop when their
    handle is set to null. Your run method should
    constantly be checking on a variable to know when to
    stop running and exit the run method. In this case,
    you could check on the drawIterations variable to see
    if it's null.<br>
    <br>Even using the following line on my run method I get the the same problem:
    <br>
    <br>while (myThread == drawIterations && drawIterations!=null && halfStep < 2 * totalIterations) {
    <br>...
    <br>
    <br>Here's the whole method:
    <br>(actually there are 2 graphs being drawn and the second is only refreshed every 2 steps:)
    <br>
    <br>     <br>public void run() {
         <br>  Thread myThread = Thread.currentThread();
         <br>  int totalIterations = transientIterations +iterationsToDraw ;
              <br>  while (myThread == drawIterations && drawIterations!=null && halfStep < 2 * totalIterations) {
              <br>     computeNextHalfIterationGraphPoint( );
              <br>      if (!TRANSIENT_IS_ENABLED || halfStep >= 2*transientIterations ) {// is     not in transient calculations
              <br>                       graphArea1.repaint();
              <br>                       if (halfStep%2 ==0 ) graphArea2.repaint();
              <br>                       if (halfStep < 2*totalIterations){//no need to execute the following block if at last iteration point
                   <br>                         if (lastIterationPointsFallOutsideGraphArea(toEndCPButtonActive)) break;
                        <br>          try {
                             <br>                      Thread.sleep(sleepingTimeBetweenHalfIterationRendering);
                             <br>                      if (threadInterrupted ){//if clause included to avoid stepping into a synchronized block if unnecessary
                                  <br>                        synchronized (this) {
                                       <br>                          while (threadInterrupted && myThread==drawIterations ) wait();
                                                      <br>    }
    <br>                                               }
         <br>                                   } catch (InterruptedException e) {
              <br>                                     break;
                   <br>                         }     
                        <br>               }
    <br>                            }
         <br>        stopThread();
         <br>     }
    <br>

Maybe you are looking for

  • Error while deploying .sda file using t-code Sdoe_upload_archive

    Dear all,          After transport all the SWDC to another client, i try to deploy the sca file using the tcode Sdoe_upload_archive and i am getting this error : " DataObject Transid '005056C000081DDD9BA073B0B4974E15' doesnot exist/is inactive in DOE

  • Power Mac G5 Dual 2.7GHz

    I've had this G5 (2.7GHz, 1.5GB Apple RAM) since around February or March and for quite some time it made two clicking sounds and that was it. Today at around 6:40 I was just about to go pick up another G5 also a 2.7GHz for parts to replace the power

  • Top Sites at Safari Won't Stay

    I only got this laptop for weeks and I can't figure out how to keep my picked top sites at Safari. I clicked the EDIT button and pushed the pin for all the sites I wish to be kept at top sites but they will run after I restart my laptop. I read a thr

  • Error when trying to  download from OpenLibrary

    Every time I try to download a book from OpenLibrary or any other site with a similar setup I get a "Page not found' or equivalent error. It's as if a port or program is blocked by a firewall but I've made all the exceptions and even tried turning th

  • Feed no longer valid?

    Hum, I updated podpress for wordpress and now it seems my iTunes podcast feed is not working http://mousechat.net/?feed=podcast http://itunes.apple.com/podcast/mousechat-net-a-weekly-disney/id395503030 Any ideas? Thanks, Steve