Major cleanup of Utils class.
[trakem2.git] / ini / trakem2 / utils / Dispatcher.java
blob2512d6d2338da549ee996ca2cbb7b901845b57e7
1 /**
3 TrakEM2 plugin for ImageJ(C).
4 Copyright (C) 2008 Albert Cardona.
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt )
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 You may contact Albert Cardona at acardona at ini.phys.ethz.ch
20 Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
21 **/
23 package ini.trakem2.utils;
25 import java.util.ArrayList;
26 import javax.swing.SwingUtilities;
28 public class Dispatcher extends Thread {
29 private final class Task {
30 Runnable run;
31 boolean swing;
32 Task(Runnable run, boolean swing) {
33 this.run = run;
34 this.swing = swing;
37 private final ArrayList<Task> tasks = new ArrayList<Task>();
38 private final Lock lock = new Lock();
39 private boolean go = true;
41 public Dispatcher(String tag) {
42 super("T2-Dispatcher" + (null != tag ? " " + tag : ""));
43 setPriority(Thread.NORM_PRIORITY);
44 setDaemon(true);
45 start();
47 public Dispatcher() {
48 this(null);
50 public void quit() {
51 this.go = false;
52 synchronized (this) { notify(); }
54 public boolean isQuit() {
55 return go;
58 private boolean accept = true;
60 public void quitWhenDone() {
61 accept = false;
62 quit();
65 /** Submits the task for execution and returns immediately. */
66 public void exec(final Runnable run) { exec(run, false); }
67 public void execSwing(final Runnable run) { exec(run, true); }
68 public void exec(final Runnable run, final boolean swing) {
69 if (!accept) {
70 Utils.log2("Dispatcher: NOT accepting more tasks!");
71 return;
73 synchronized (lock) {
74 lock.lock();
75 tasks.add(new Task(run, swing));
76 lock.unlock();
78 synchronized (this) { notify(); }
80 /** Executes one task at a time, in the same order in which they've been received. */
81 public void run() {
82 while (go || (!accept && tasks.size() > 0)) {
83 try {
84 synchronized (this) { wait(); }
85 if (!go) return;
86 while (tasks.size() > 0) {
87 Task task = null;
88 synchronized (lock) {
89 lock.lock();
90 if (tasks.size() > 0) {
91 task = tasks.remove(0);
93 lock.unlock();
95 if (null == task) continue;
96 try {
97 if (task.swing) SwingUtilities.invokeAndWait(task.run);
98 else task.run.run();
99 } catch (Throwable t) { IJError.print(t); }
101 } catch (Throwable e) { IJError.print(e); }