KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > foxtrot > AsyncTask


1 /**
2  * Copyright (c) 2002-2005, Simone Bordet
3  * All rights reserved.
4  *
5  * This software is distributable under the BSD license.
6  * See the terms of the BSD license in the documentation provided with this software.
7  */

8
9 package foxtrot;
10
11 import javax.swing.SwingUtilities JavaDoc;
12
13 /**
14  * A time-consuming task to be executed asynchronously by {@link AsyncWorker}. <br />
15  * Users must implement the {@link #run} method as they would do with Task.
16  * Exceptions and Errors thrown by the <code>run()</code> method will <strong>not</strong>
17  * be rethrown automatically by {@link AsyncWorker#post(AsyncTask)}.
18  * Instead, {@link #getResultOrThrow} should be called, normally from inside
19  * {@link #finish()}. <br />
20  * The {@link #finish()} method is called in the Event Dispatch Thread when the
21  * Task is finished.
22  * AsyncTasks cannot be reused, that is, it is not safe to pass the same instance to
23  * two consecutive calls to {@link AsyncWorker#post(AsyncTask)}.
24  * Example:
25  * <pre>
26  * AsyncTask task = new AsyncTask()
27  * {
28  * public Object run() throws Exception
29  * {
30  * // Called in a worker thread
31  * Thread.sleep(1000);
32  * return new ArrayList();
33  * }
34  *
35  * public void finish()
36  * {
37  * // Called in the Event Dispatch Thread
38  * try
39  * {
40  * List result = (List)getResultOrThrow();
41  * // Do something with the List
42  * }
43  * catch (Exception x)
44  * {
45  * // Report exception to the user, or just log it
46  * }
47  * }
48  * });
49  * </pre>
50  * @see AsyncWorker
51  * @version $Revision: 1.2 $
52  */

53 public abstract class AsyncTask extends Task
54 {
55    /**
56     * Called in the Event Dispatch Thread after this AsyncTask is finished, to
57     * allow the coder to update Swing components safely, for example with the results
58     * of the execution of this AsyncTask.
59     * @see #getResultOrThrow()
60     */

61    public abstract void finish();
62
63    void postRun()
64    {
65       SwingUtilities.invokeLater(new Runnable JavaDoc()
66       {
67          public void run()
68          {
69             finish();
70          }
71       });
72    }
73 }
74
Popular Tags