1 /* 2 * $Id$ 3 * 4 * Copyright 2007 Bruno Lowagie. 5 * 6 * This library is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU Lesser General Public 8 * License as published by the Free Software Foundation; either 9 * version 2.1 of the License, or (at your option) any later version. 10 * 11 * This library is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 * Lesser General Public License for more details. 15 * 16 * You should have received a copy of the GNU Lesser General Public 17 * License along with this library; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 */ 20 21 package com.lowagie.rups.model; 22 23 import javax.swing.SwingUtilities; 24 25 /** 26 * Allows you to perform long lasting tasks in background. 27 * If we ever move to Java 6, we should use the SwingWorker class 28 * (included in the JDK) instead of this custom Event Dispatching 29 * code. 30 */ 31 32 public abstract class BackgroundTask { 33 34 /** 35 * Inner class that holds the reference to the thread. 36 */ 37 private static class ThreadWrapper { 38 private Thread thread; ThreadWrapper(Thread t)39 ThreadWrapper(Thread t) { thread = t; } get()40 synchronized Thread get() { return thread; } clear()41 synchronized void clear() { thread = null; } 42 } 43 44 /** A wrapper for the tread that executes a time-consuming task. */ 45 private ThreadWrapper thread; 46 47 /** 48 * Starts a thread. 49 * Executes the time-consuming task in the construct method; 50 * finally calls the finish(). 51 */ BackgroundTask()52 public BackgroundTask() { 53 final Runnable doFinished = new Runnable() { 54 public void run() { finished(); } 55 }; 56 57 Runnable doConstruct = new Runnable() { 58 public void run() { 59 try { 60 doTask(); 61 } 62 finally { 63 thread.clear(); 64 } 65 SwingUtilities.invokeLater(doFinished); 66 } 67 }; 68 Thread t = new Thread(doConstruct); 69 thread = new ThreadWrapper(t); 70 } 71 72 /** 73 * Implement this class; the time-consuming task will go here. 74 */ doTask()75 public abstract void doTask(); 76 77 /** 78 * Starts the thread. 79 */ start()80 public void start() { 81 Thread t = thread.get(); 82 if (t != null) { 83 t.start(); 84 } 85 } 86 87 /** 88 * Forces the thread to stop what it's doing. 89 */ interrupt()90 public void interrupt() { 91 Thread t = thread.get(); 92 if (t != null) { 93 t.interrupt(); 94 } 95 thread.clear(); 96 } 97 98 /** 99 * Called on the event dispatching thread once the 100 * construct method has finished its task. 101 */ finished()102 public void finished() { 103 } 104 } 105