Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / April 2007

Tip: Looking for answers? Try searching our database.

calling SwingWorker cancel in WindowClosing event handler

Thread view: 
yancheng.cheok@gmail.com - 31 Mar 2007 16:50 GMT
hello,

i realize that when after i call SwingWorker cancel and try to wait
until the task is really canceled (through SwingWorker.get), i will
get exception as stated in http://java.sun.com/docs/books/tutorial/uiswing/concurrency/cancel.html

Note: If get is invoked on a SwingWorker object after its background
task has been cancelled, java.util.concurrent.CancellationException is
thrown.

Hence, i was wondering after the CancellationException caught, when
the time the next statement is executed, does the task is really
cancelled?

thanks

   private void formWindowClosing(java.awt.event.WindowEvent evt)
{
// TODO add your handling code here:
       try
       {
           marketTask.cancel(false);
           marketTask.get();
       }
       catch(InterruptedException exp) {
       }
       catch(java.util.concurrent.ExecutionException exp)
{
       }
       catch(java.util.concurrent.CancellationException exp)
{
       }

// So, does market Task really cancelled???
   }
Andrew Thompson - 31 Mar 2007 17:48 GMT
On Apr 1, 1:50 am, yancheng.ch...@gmail.com wrote:
> hello,

G'day!  Just thought I should point out that not one of
the three* posts you made, made much sense to me.  But
then, anything short of compilable code leaves me a
little confused (it's a personal problem, and hey, I
am trying to deal with it, but..) I suggest you post
some code that is complete and compilable, to demonstrate
the problem.  Or, to be more exact and specific, I
recommend an SSCCE.
<http://www.physci.org/codes/sscce.html>

> i realize that when after i call ..

But as an aside.  The word 'I' should alway be upper
case.  It is a small matter, but if you can help
people to read and understand your posts, it can
increase the chance of getting help.

(* And ..please refrain from making three identical
posts, in future.)

Andrew T.
Andrew Thompson - 01 Apr 2007 08:24 GMT
> On Apr 1, 1:50 am, yancheng.ch...@gmail.com wrote:
>
> > hello,
>
> G'day!  

And to 'HappySnack' who sent me an email.
It was deleted unread.  Got something to say?
Say it here* where it matters more than one iota..

* Or 'on the original thread' - AFAIR, the
email 'sub' related to this thread.

Andrew T.
yancheng.cheok@gmail.com - 01 Apr 2007 14:32 GMT
I am sorry. This is because I get error from google group even I press
send yesterday. Hence, I thought the previous message is lost. So, I
press it for several times... :P

> On Apr 1, 1:50 am, yancheng.ch...@gmail.com wrote:
>
[quoted text clipped - 21 lines]
>
> Andrew T.
Knute Johnson - 31 Mar 2007 17:57 GMT
> hello,
>
[quoted text clipped - 31 lines]
> // So, does market Task really cancelled???
>     }

You will know that marketTask is canceled by checking the return value
of cancel().  Calling get() will not block.  It will just throw a
CancellationException.

From the docs:

cancel

public final boolean cancel(boolean mayInterruptIfRunning)

    Attempts to cancel execution of this task. This attempt will fail
if the task has already completed, has already been cancelled, or could
not be cancelled for some other reason. If successful, and this task has
not started when cancel is called, this task should never run. If the
task has already started, then the mayInterruptIfRunning parameter
determines whether the thread executing this task should be interrupted
in an attempt to stop the task.

Signature

Knute Johnson
email s/nospam/knute/

yancheng.cheok@gmail.com - 01 Apr 2007 14:35 GMT
is there anyway, i can wait for the swing worker to really complete,
after i call the cancel method? this is my swing worker will only
terminate, only if i call cancel()...

           while (! isCancelled()) {
        // swing worker is doing something....
           }

> You will know that marketTask is canceled by checking the return value
> of cancel().  Calling get() will not block.  It will just throw a
> CancellationException.

Is there any way I can "wait", until the task is really completed
after I make a call to cancel? My task is running in a infinity loop :

>  From the docs:
>
[quoted text clipped - 14 lines]
> Knute Johnson
> email s/nospam/knute/
Knute Johnson - 01 Apr 2007 18:34 GMT
> is there anyway, i can wait for the swing worker to really complete,
> after i call the cancel method? this is my swing worker will only
[quoted text clipped - 3 lines]
>         // swing worker is doing something....
>             }

No.

>> You will know that marketTask is canceled by checking the return value
>> of cancel().  Calling get() will not block.  It will just throw a
>> CancellationException.
>
> Is there any way I can "wait", until the task is really completed
> after I make a call to cancel? My task is running in a infinity loop :

If your task is an infinite loop then you don't need SwingWorker.  Just
use a Runnable and start it running with a thread.  Then when you are
done, signal it to stop either by interrupting it, setting a flag or
causing some sort of exception to be thrown.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test5 implements Runnable {
    volatile boolean runFlag = true;
    Thread thread;

    public void run() {
        // once started this thread will run as long as runFlag is true
        while (runFlag) {
            // do your processing here, this example just sleeps
            System.out.println("processing...");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException ie) { }
        }
        System.out.println("process stopped");
    }

    public static void main(String[] args) {
        // create the gui
        Runnable r = new Runnable() {
            public void run() {
                final test5 t5 = new test5();
                final JFrame f = new JFrame();
                // leave the window open when the X is clicked
                f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                f.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent we) {
                        // start another thread here so as not to
                        //  block the EDT
                        Runnable r = new Runnable() {
                            public void run() {
                                // tell the loop to end
                                t5.runFlag = false;
                                // join this thread and the task thread
                                // this will wait here until the other
                                //  thread is finished or this thread is
                                //  interrupted
                                try {
                                    t5.thread.join();
                                } catch (InterruptedException ie) { }
                                // close the program
                                System.exit(0);
                            }
                        };
                        // start the runnable above to end the program
                        new Thread(r).start();
                        // show a dialog to let users know what is
                        //  happening
                        JDialog d = new JDialog(f,false);
                        d.setLocationRelativeTo(f);
                        JLabel l = new JLabel("Shutting Down");
                        d.add(l);
                        d.pack();
                        d.setVisible(true);
                    }
                });
                f.setSize(200,150);
                f.setVisible(true);

                // start the task running
                t5.thread = new Thread(t5);
                t5.thread.start();
            }
        };
        EventQueue.invokeLater(r);
    }
}

Signature

Knute Johnson
email s/nospam/knute/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.