aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/plugin/desktoputil/SwingWorker.java
blob: fc64a98ddd8bfde5e4f915f7edef052aef7b7b1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 *
 * Based on the 3rd version of SwingWorker (also known as SwingWorker 3), an
 * abstract class that you subclass to perform GUI-related work in a dedicated
 * thread. For instructions on using this class, see:
 *
 * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
 *
 * Note that the API changed slightly in the 3rd version:
 * You must now invoke start() on the SwingWorker after
 * creating it.
 */
package net.java.sip.communicator.plugin.desktoputil;

import java.util.concurrent.*;

import javax.swing.*;

import net.java.sip.communicator.util.*;

/**
 * Utility class based on the javax.swing.SwingWorker. <tt>SwingWorker</tt> is
 * an abstract class that you subclass to perform GUI-related work in a
 * dedicated thread. In addition to the original SwingWorker this class takes
 * care of exceptions occurring during the execution of the separate thread. It
 * will call a catchException() method in the Swing thread if an exception
 * occurs.
 *
 * @author Yana Stamcheva
 * @author Lyubomir Marinov
 */
public abstract class SwingWorker
{
    /** Logging instance for SwingWorker */
    private final static Logger logger = Logger.getLogger(SwingWorker.class);

    /**
     * The <tt>ExecutorService</tt> which is shared by the <tt>SwingWorker</tt>
     * instances for the purposes of controlling the use of <tt>Thread</tt>s.
     */
    private static ExecutorService executorService;

    /**
     * The <tt>Callable</tt> implementation which is (to be) submitted to
     * {@link #executorService} and invokes {@link #construct()} on behalf of
     * this <tt>SwingWorker</tt>.
     */
    private final Callable<Object> callable;

    /**
     * The <tt>Future</tt> instance which represents the state and the return
     * value of the execution of {@link #callable} i.e. {@link #construct()}.
     */
    private Future<?> future;

    /**
     * Start a thread that will call the <code>construct</code> method
     * and then exit.
     */
    public SwingWorker()
    {
        callable
            = new Callable<Object>()
            {
                public Object call()
                {
                    Object value = null;

                    try
                    {
                        value = construct();
                    }
                    catch (final Throwable t)
                    {
                        if (t instanceof ThreadDeath)
                            throw (ThreadDeath) t;
                        else
                        {
                            // catchException
                            SwingUtilities.invokeLater(
                                    new Runnable()
                                    {
                                        public void run()
                                        {
                                            catchException(t);
                                        }
                                    });
                        }
                    }

                    // We only want to perform the finished if the thread hasn't
                    // been interrupted.
                    if (!Thread.currentThread().isInterrupted())
                        // finished
                        SwingUtilities.invokeLater(
                                new Runnable()
                                {
                                    public void run()
                                    {
                                        finished();
                                    }
                                });

                    return value;
                }
            };
    }

    /**
     * Called on the event dispatching thread (not on the worker thread)
     * if an exception has occurred during the <code>construct</code> method.
     *
     * @param exception the exception that has occurred
     */
    protected void catchException(Throwable exception)
    {
        logger.error("unhandled exception caught", exception);
    }

    /**
     * Computes the value to be returned by {@link #get()}.
     */
    protected abstract Object construct()
        throws Exception;

    /**
     * Called on the event dispatching thread (not on the worker thread)
     * after the <code>construct</code> method has returned.
     */
    protected void finished()
    {
    }

    /**
     * Return the value created by the <code>construct</code> method.
     * Returns null if either the constructing thread or the current
     * thread was interrupted before a value was produced.
     *
     * @return the value created by the <code>construct</code> method
     */
    public Object get()
    {
        Future<?> future;

        synchronized (this)
        {
            /*
             * SwingWorker assigns a value to the future field only once and we
             * do not want to invoke Future#cancel(true) while holding a lock.
             */
            future = this.future;
        }

        Object value = null;

        if (future != null)
        {
            boolean interrupted = false;

            do
            {
                try
                {
                    value = future.get();
                    break;
                }
                catch (CancellationException ce)
                {
                    break;
                }
                catch (ExecutionException ee)
                {
                    break;
                }
                catch (InterruptedException ie)
                {
                    interrupted = true;
                }
            }
            while (true);
            if (interrupted) // propagate
                Thread.currentThread().interrupt();
        }

        return value;
    }

    /**
     * A new method that interrupts the worker thread.  Call this method
     * to force the worker to stop what it's doing.
     */
    public void interrupt()
    {
        Future<?> future;

        synchronized (this)
        {
            /*
             * SwingWorker assigns a value to the future field only once and we
             * do not want to invoke Future#cancel(true) while holding a lock.
             */
            future = this.future;
        }

        if (future != null)
            future.cancel(true);
    }

    /**
     * Start the worker thread.
     */
    public void start()
    {
        ExecutorService executorService;

        synchronized (SwingWorker.class)
        {
            if (SwingWorker.executorService == null)
                SwingWorker.executorService = Executors.newCachedThreadPool();
            executorService = SwingWorker.executorService;
        }

        synchronized (this)
        {
            if (future == null || future.isDone())
                future = executorService.submit(callable);
            else
                throw new IllegalStateException("future");
        }
    }
}