views:

68

answers:

2

I am relatively new to multi-threading and want to execute a background task using a Swingworker thread - the method that is called does not actually return anything but I would like to be notified when it has completed.

From all the tutorials that I have seen online about using SwingWorkers are created such as

new SwingWorker<String, Void>; 

Would declaring mine as Void, Void be suitable as there is no data being returned?

The code I have so far doesn't appear to be working:

private void crawl(ActionEvent evt)
{
    try
    {
    SwingWorker<Void, Void> crawler = new SwingWorker<Void, Void>()
    {
        @Override
        protected Void doInBackground() throws Exception
        {
            Discoverer discover = new Discoverer();
            discover.crawl();
            return null;
        }

        @Override
        protected void done()
        {
            JOptionPane.showMessageDialog(jfThis, "Finished Crawling", "Success", JOptionPane.INFORMATION_MESSAGE);
        }

    };
    crawler.execute();
    }
    catch (Exception ex)
    {
         JOptionPane.showMessageDialog(this, ex.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
    }
}

Any feedback/advice would be greatly appreciated as multi-threading is a big area of programming that I am weak in.

+2  A: 

The code seems ok... It should work. Maybe the crawl method never finishes... What happens if you debug the code and have it run until the line where you return null and see if the crawl method ever finishes...

Savvas Dalkitsis
Discoverer is in a seperate project in netbeans and I had added it as a shared project - however the libraries that this depended on were not present in the GUI so this was throwing errors which once copied to the GUI project resolved this and all is working correctly.
Malachi
+1  A: 

I would recommend monitoring the status of your crawl method (does it ever finish?) as well as wrapping it within a try { ... } catch block WITHIN your doInBackground. Either that or call "get()" from your done method. Either way should allow you to catch any exceptions that are thrown during crawling.

jsight