Squiz Matrix  4.12.2
 All Data Structures Namespaces Functions Variables Pages
MatrixSwingWorker.java
1 
16 package net.squiz.matrix.ui;
17 
18 import javax.swing.SwingUtilities;
19 
32 public abstract class MatrixSwingWorker {
33  private Object value; // see getValue(), setValue()
34  private Thread thread;
35 
40  private static class ThreadVar {
41  private Thread thread;
42  ThreadVar(Thread t) { thread = t; }
43  synchronized Thread get() { return thread; }
44  synchronized void clear() { thread = null; }
45  }
46 
47  private ThreadVar threadVar;
48 
53  protected synchronized Object getValue() {
54  return value;
55  }
56 
60  private synchronized void setValue(Object x) {
61  value = x;
62  }
63 
67  public abstract Object construct();
68 
73  public void finished() {
74  }
75 
80  public void interrupt() {
81  Thread t = threadVar.get();
82  if (t != null) {
83  t.interrupt();
84  }
85  threadVar.clear();
86  }
87 
95  public Object get() {
96  while (true) {
97  Thread t = threadVar.get();
98  if (t == null) {
99  return getValue();
100  }
101  try {
102  t.join();
103  }
104  catch (InterruptedException e) {
105  Thread.currentThread().interrupt(); // propagate
106  return null;
107  }
108  }
109  }
110 
111 
116  public MatrixSwingWorker() {
117  final Runnable doFinished = new Runnable() {
118  public void run() { finished(); }
119  };
120 
121  Runnable doConstruct = new Runnable() {
122  public void run() {
123  try {
124  setValue(construct());
125  }
126  finally {
127  threadVar.clear();
128  }
129 
130  SwingUtilities.invokeLater(doFinished);
131  }
132  };
133 
134  Thread t = new Thread(doConstruct);
135  threadVar = new ThreadVar(t);
136  }
137 
141  public void start() {
142  Thread t = threadVar.get();
143  if (t != null) {
144  t.start();
145  }
146  }
147 }