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

Similar Messages

  • SwingWorker done() is called BEFORE process() when publish() used

    I'm using SwingWorker to build a list of files by recursively searching a directory. As a file is found I call publish(file). In my process() method I add the file(s) to a list model, which updates a JList. I also have a PropertyChangeListener attached to the SwingWorker so I know when its done. The listener calls listModel.getSize() when done, so I can determine wheter to enable a 'Clear List' button. When only a few files are found, SwingWorker is done() before process() has added the files to the model, so the size is 0 and the button is not enabled.
    Mu question is how can I get SwingWorker to call process() before calling done()?
    Thanks

    Mu question is how can I get SwingWorker to call
    process() before calling done()?I have run into the same problem. It's ugly. The least Java could do is offer a flush() method. At best, they'd fix this problem and flush any publish()ed objects before calling done(). I've worked around it for now with a hack. I simply publish a null to signal completion in doInBackground(). I don't even override done() any more. Of course, I'm assuming publish() order is maintained (evidence so far supports this assumption).
    The only other option I'm aware of is invokeLater().
    Andrew

  • Using onestep dvd form movie (which I have done, successfully, many time before but now, the comuter ejects the disk 5 minutes before it is finished, and teh disk is blank, any thoughts anyone?mes before

    with i dvd, using onestep dvd from movie (which I have done, successfully, many time before) but now the comuter ejects the disk 5 minutes before it is finished, and the disk is blank, any thoughts anyone?

    with i dvd, using onestep dvd from movie (which I have done, successfully, many time before) but now the comuter ejects the disk 5 minutes before it is finished, and the disk is blank, any thoughts anyone?

  • I'm trying to share to Media Browser a 20 minute still slide show with music and text. I have tried several times to save at 1080 HD, but just before it's finished, a message box pops up saying "File already open with write permission."  What's this mean?

    I'm trying to finalize/share to Media Browser a 20 minute still slide show with music and text. I'd like to finalize it 1080 hd and have tried several times, but just before it's finished, a message box pops up saying it can't be done because "File already open with with write permission."  What does this mean?  All files are closed; this iMovie project is the only thing open.  Does it mean one of the song files from iTunes? And should I just settle for saving it as a "large" file, which is what I'm trying right now?
    Thanks,
    Jamie

    Hi
    Error -49 opWrErr  File already open with write permission
    Trash the preference files while application is NOT Running.
    from Karsten Schlüter
    Some users notice on exporting larger projects from within iMovie that this operation is aborted with an 'error -49'
    This issue occours only on MacOs machines using 10.7x
    try switching-off the Local Mobile Backup
    in Terminal copy/paste
    sudo tmutil disablelocal
    Re-launch Mac
    See also this post
    https://discussions.apple.com/thread/4434104?tstart=0
    Yours Bengt W

  • I am very disappointed with iTunes.  I have 1200 songs and I can't play them.  I try to play them and before one song finish a song starts playing. This then results in hearing two songs at the same time. I will like to know if you can fix this. I feel li

    I am very disappointed with iTunes.  I have 1200 songs and I can’t play them.  I try to play them and before one song finisha song starts playing. This then results in hearing two songs at the same time.I will like to know if you can fix this. I feel like listening with the iTunesplayer is useless.

    I don't know man I too hope apple will do something this new I-tunes blow my top lost my whole tune!!!

  • I am getting a message the something called Completer wants to finish installing. I get this whenever I log in. What the **** is it?

    I am getting a message the something called Completer wants to finish installing. I get this whenever I log in. What the **** is it?

    It's adware. Click here and follow the instructions, or if they don't cover that specific type of adware, these ones. If you're willing to use a tool to remove it(you don't need to, but may find it easier), you can instead run Adware Medic; this link is a direct download.
    (119897)

  • Method call before visual web jsf page loads

    Hi All.....
    I have written a method in a java class that accesses the mysql backend db to check if a process is still running. If the process is still running, a JOptionPane is produced informing the user of this and offers an <ok> option(to check the process status again) and a <cancel> option(to redirect the user to the homepage). If the process is completed, I want the page to just load as normal. I want this method to be called before the visual web jsf page loads. I have the method call in the super_init() method of the page and everything seemed to be working fine, the problem I have run into is that if I set the value in the db to show the process is running, the JOptionPane is produced(like it should be), and then if I set the value to show the process has completed and choose <ok> from the pane, the page loads.....this is what I want. Now, after the page loads, if I set the value in the db to show the process is running again, the JOptionPane is produced again right after I apply the changes to the db edit!!!!. I don't know why this is happening. Should I be calling the method from somewhere other the super_init()????? I have tried the method call in the prerender(), preprocess(), and destroy() methods all with the same results.
    Anyone have any ideas on what the problem could be??
    Thanks in advance.
    Silgd

    The Java part of a JSP/Servlet based webapplication runs physically at the server machine.
    Only the HTML/CSS/JS part which is generated by the webapplication and sent to the client physically runs at the client machine.
    JOptionPane is a Java Swing component which thus runs at the server machine. So you as client would only see it when both the server and the client runs at physically the same machine. Which is often only the case in development environment and doesn´t occur in real life! There is normally means of two physically different machines connected through the network/internet.
    To solve your actual problem, look for Ajax poll techniques. To display an alert or confirm dialogue in the client side, you use Javascript for this.

  • Action method called before the listener

    hi all;
    i have a command_link as follows:
    <h:command_link action="#{someBean.someMethod}" >
         <f:parameter name="param" value="0"/>
         <h:output_text value="#{someBean.someProperty}"/>
         <f:action_listener type="com.myListener" />
    </h:command_link>
    my problem is that the listener is called AFTER the bean method is called. i need my bean to use data that is set by the listener so i need the listener to be called BEFORE that method.
    on EA4 i used the getPhaseID but now its gone and i cant seem to find the proper replacement.
    i tried the immediate="true" attribute on the command_link with no success, the results were the same.
    any help is appreciated.

    I believe that what's really going on here is that
    "action" should always be processed after all action
    listeners, when, in fact, it's always processed first.
    I'll raise this on the EG.
    AIUI it's even more confusing than your description implies. There seem to be three things
    that can be triggered from a <command_button> or <command_link>:
    1. ActionListeners registered using a nested <action_listener> tag.
    2. An action listener method declared using the actionlistener attribute.
    3. An action method declared using the action attribute.
    I don't think the spec defines a relative ordering for all of these possible event handlers, but I
    think it works like this:
    A. All the action listeners are called in an undefined order. This takes care of all those in
    category (1) above. Since one of the listeners is the system-defined default listener,
    at some point during this processing, the action method (which is REALLY the application code)
    is also called. However, since the spec is vague, you don't really know where this happens relative to
    the other listeners.
    B. The method referred by the actionlistener attribute in category 2 above is called.
    I would have thought that the most intuitive order would be:
    1. All of the action listeners, whether added using <action_listener> or declared using the
    actionlistener attribute.
    2. The method referred to by the action attribute (i.e. the real application code).
    I think the current implementation, where (2) is done by a system-defined actionlistener, gets in the
    way of achieving this, and that would have to change in order to produce a well-defined result.

  • HT201250 How do you stop a Macbookpro with OSX 10.7.5 from turning off or logging off before timemachine is finished with the backup even though I have changed settings for energy management to "never" shutdown when plugged in to an outlet?

    My problem is my Macbookpro mid 2010 with OSX 10.7.5 seems to turn off or logs off before timemachine is finished with the backup even though I have changed settings for energy management to "never" shutdown when plugged in to an outlet?

    I had this problem on an IMac and I finally found a solution in an unlikely place. The problem was a security setting. I don't remember right this moment the exact setting and I am not on that machine right now but when I am I will try to retrace my steps to the fix. In the meantime check your security settings and any browser or browser extensions for computer log off settings. These settings are intended to prevent unauthorized use and incidentally screw up your backups. Hope this helps.

  • EXIT_SAPLIE01_007 is called BEFORE mblnr is created, so how to get mblnr ??

    In a reply to a previous question, Rich suggested intercepting the MIGO goods receipt posting process by activating enhancement IQSM0007 which uses function module EXIT_SAPLIE01_007 and include ZXQSMU06.
    I did this, but the problem is:
    <b>This exit is called BEFORE the actual mseg mblnr number is created.</b>
    So how can I find out what mseg mblnr is created in the posting process ?
    If I don't know this, I don't know what mseg record to add my custom fields to - the ones that I capture on a custom screen inside the exit ...
    Thanks for any advice or clarification anyone can provide.
    djh

    Hi,
    You can use the exit EXIT_SAPLMBMB_001 OR BADI MB_DOCUMENT_BADI method MB_DOCUMENT_UPDATE...
    In this user exit the MBLNR number is populated ..
    This user exit is called in the FM MB_POST_DOCUMENT..
    The MB_POST_DOCUMENT is called in update task..
    If you want to debug switch on the update debugging..
    THanks,
    Naren

  • ServletStartup called before application startup

    I need to load two servlets on startup. They both depend on my
              application being up, however the servletStartup is called before the
              other startup classes.
              Previous posts seemed to indicate that there was no definitive way to
              control startup order.
              Any suggestions?
              I thought about calling weblogic.servlet.utils.ServletStartup directly,
              but can't find any javadocs and don't think it's public.
              I don't really want to "hit" the servlets using urlConnection, although
              that's the only thing I can think of.
              Any way that startup "ordering" could be added in a future version? It
              seems pretty useful (necessary) to me.
              Thanks,
              Robert Quinn
              

    Thanks for your help. I would agree that a better system for ordering startup classes would
              helpful.
              Alexander Petrushko wrote:
              > Robert Quinn wrote:
              >
              > > I need to load two servlets on startup. They both depend on my
              > > application being up, however the servletStartup is called before the
              > > other startup classes.
              > >
              > > Previous posts seemed to indicate that there was no definitive way to
              > > control startup order.
              >
              > The only way to control the order of startup classes being executed is to
              > register
              > them in the same statement in the order you want, like so
              >
              > weblogic.system.startupClass.myApp=com.foo.bar.MyApp,weblogic.servlet.utils.ServletStartup
              >
              > weblogic.system.startupArgs.myApp=param1=foo,param2=foo,servlet=com.foo.bar.MyServlet
              >
              > Both MyApp and ServletStartup will receive the same hashtable with
              > param1/param2/servlet
              > args but MyApp will be executed first. The problem with this approach is
              > that this registration stanza tends to get very messy as startup classes
              > are added.
              >
              > This "feature" can definitely use some improvement, namely having another
              > property to specify the order of execution a la
              >
              > weblogic.system.startupClass.myApp=...
              > weblogic.system.queueOrder.myApp=1
              >
              > weblogic.system.startupClass.myOtherApp=...
              > weblogic.system.queueOrder.myOtherApp=2
              >
              > Regards,
              >
              > Alex.
              >
              > --
              > mailto:[email protected] // Consulting services available
              

  • The call was cancelled by the caller before the remote party answered

    Hi,
    We have a Lync 2010 Enterprise deployment in a single site with 2 FE and Mediation Server collocated.
    When dialling a number from a PSTN phone the call gets routed via our PBX/PBX Gateway/Mediation Server/FE Server to the desktop Lync client successfully.
    As soon as the user answers the call with the Lync client the call 'hangs' and terminates without hearing anything on either side.
    The snooper logs show:
    Error:
    SIP/2.0 487 Request Terminated
    Partial Content:
    User-Agent: UCCAPI/4.0.7577.4398 OC/4.0.7577.4398 (Microsoft Lync 2010)
    Ms-client-diagnostics: 52092;reason="The call was cancelled by the caller before the remote party answered"
    Content-Length: 0
    Please help?
    Vinkie

    What kind of gateway are you using to connect to your PBX and how?  What is your media set to?  G.711 μ-law or a-law?  I'd check media settings there as a starting point. 
    Please remember, if you see a post that helped you please click "Vote As Helpful" and if it answered your question please click "Mark As Answer".

  • Apps Adapter API is called before Db Adapter inserting data

    Hi All,
    I am using a bpel process which calls db adapter to insert/update data in staging table, after this activity i am calling a Apps Adapter PLSQL API where it takes the data from staging table and performs some functionality. But the problem here is Apps adapter PlSQL API is getting called before isnerting data in staging table.
    Below are the steps in BPEL Process,
    1. receive activity
    2. data transformation
    3. invokes db adapter through merge operation to insert/update in staging tables
    4. invoke Apps Adapter PLSQL API
    Error is thrown at Apps Adapter invoke activity, saying null values. presently we used a wait activity before invoking apps adapter.
    Do the invoke of Apps Adapeter doesnt happen after Db Adapter inserting data?
    Thanks,
    Ra

    Hi Team,
    Even I faced the same problem.
    I am checking, do we have any configuration setting to avaoid these kind of problem.
    Even my process has point 2 & 3 in a single sequence and point 4 in another sequence.
    Any help to resolve this problem is greatly appreciated.
    Thanks for your help in adavance.
    Cheers
    Chandru

  • I accidently "x" off the download of firefox 4 before it had finished and now the home page doesn't work, i tried redownloading firefox but that didn't work is there a way i can resume the download?

    I accidently "x" off the download of firefox 4 before it had finished and now the home page doesn't work. it loads but then wont let me search from it? i tried redownloading firefox but that didn't work is there a way i can resume the previous download?

    Your More system details list show that you run the latest Firefox 4.0.1 version.<br />
    You can check that via Help > About Firefox and on the Help > Troubleshooting Information page.
    A possible cause is security software (firewall) that blocks or restricts Firefox or the plugin-container process without informing you, possibly after detecting changes (update) to the Firefox program.
    Remove all rules for Firefox from the permissions list in the firewall and let your firewall ask again for permission to get full unrestricted access to internet for Firefox and the plugin-container process.
    See:
    * https://support.mozilla.com/kb/Server+not+found
    * https://support.mozilla.com/kb/Firewalls
    If you posted from another computer then download the full version and uninstall the currently installed version.
    Download a fresh Firefox copy and save the file to the desktop.
    * Firefox 4.0.x: http://www.mozilla.com/en-US/firefox/all.html
    * Uninstall your current Firefox version.
    * Do not remove personal data when you uninstall the current version.
    Remove the Firefox program folder before installing that newly downloaded copy of the Firefox installer.
    * It is important to delete the Firefox program folder to remove all the files and make sure that there are no problems with files that were leftover after uninstalling.
    Your bookmarks and other profile data are stored elsewhere in the [http://kb.mozillazine.org/Profile_folder_-_Firefox Firefox Profile Folder] and won't be affected by a reinstall, but make sure that you do not select to remove personal data if you uninstall Firefox.

  • My Iphone 4 sends emails before I am finished.. think its the space bar?

    My Iphone 4 sends emails before I am finished.. i think its the space bar? How do u fix?

    Hi Aza Din,
    To re-enable a disabled iPhone, follow this article:
    iOS: Forgotten passcode or device disabled after entering wrong passcode
    http://support.apple.com/kb/ht1212
    Take care,
    - Ari

Maybe you are looking for

  • Project Server 2010 - Manage Queue anomalies

    Morning All, I'm currently experiencing an odd situation with the Manage Queue function in our Project Server. For the entire year I've been using PS the Manage Queue has never consisted of much more than a couple of projects awaiting check-in. I log

  • How can i record a song in a karaoke music track via GB?

    how can i record a song in a karaoke music track via GB?

  • Itune 64-bit touble

    Hey so I tried to get music from my Itunes (on my computer) to my music on my Ipod touch. When I plug in my Ipod to sync it says "This Ipod cannot be used because the required software is not installed. Run the Itunes installer to remove Itunes, then

  • When exchange rate B,G are used.

    I know the exchange rate has three types . bank selling rate, bank buying rate and average rate. Can you tell me when I do a froeign currency valuation with toce:f.05 which type of exchange rate are used? And can you tell me when the bank selling rat

  • Trying to upgrade free Mac OSX Lion

    I have a new MacBook Pro and I am trying to upgrade the free Mac OSX Lion. I have followed the link on the box, filled in the various steps etc. I keep on receiving an email requesting me to validate my email address and when I follow the link it eit