--- /dev/null
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ * VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+/*\r
+ *\r
+ * @author Toni Kalajainen\r
+ */\r
+package org.simantics.utils.threads;\r
+\r
+import java.util.LinkedList;\r
+import java.util.concurrent.Semaphore;\r
+\r
+import org.simantics.utils.threads.internal.Pair;\r
+\r
+\r
+/**\r
+ * Thread manager\r
+ * \r
+ * TODO Replace with ScheduledThreadPoolExecutor\r
+ */\r
+public class WorkerThread extends Thread implements IThreadWorkQueue {\r
+\r
+ LinkedList<Pair<Runnable, Semaphore>> list = new LinkedList<Pair<Runnable, Semaphore>>();\r
+\r
+ boolean stop = false;\r
+\r
+ Semaphore finishPermit = new Semaphore(0);\r
+\r
+ public WorkerThread() {\r
+ super();\r
+ }\r
+ \r
+ public WorkerThread(String name) {\r
+ super(name);\r
+ }\r
+ \r
+ public void stopDispatchingEvents(boolean blockUntilCompleted) {\r
+ synchronized (this) {\r
+ stop = true;\r
+ notify();\r
+ }\r
+ if (blockUntilCompleted) {\r
+ try {\r
+ finishPermit.acquire();\r
+ } catch (InterruptedException e) {\r
+ }\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public void run() {\r
+ try {\r
+ while (!stop) {\r
+ while (true) {\r
+ Pair<Runnable, Semaphore> p = null;\r
+ synchronized (this) {\r
+ if(list.isEmpty())\r
+ break;\r
+ p = list.pop();\r
+ } \r
+ Runnable r = p.first;\r
+ try {\r
+ r.run();\r
+ } catch (RuntimeException rte) {\r
+ rte.printStackTrace();\r
+ }\r
+ if (p.second != null)\r
+ p.second.release(1);\r
+ }\r
+ synchronized (this) {\r
+ if (!stop)\r
+ try {\r
+ wait(10000L);\r
+ } catch (InterruptedException e) {\r
+ }\r
+ }\r
+ }\r
+ } finally {\r
+ finishPermit.release();\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public boolean syncExec(Runnable runnable) {\r
+ Semaphore s = new Semaphore(0);\r
+ synchronized (this) {\r
+ if (stop)\r
+ return false;\r
+ Pair<Runnable, Semaphore> p = new Pair<Runnable, Semaphore>(runnable, s);\r
+ list.addFirst(p);\r
+ notify();\r
+ }\r
+ return true;\r
+ }\r
+\r
+ @Override\r
+ public synchronized Thread asyncExec(Runnable runnable) {\r
+ if (stop)\r
+ return null;\r
+ Pair<Runnable, Semaphore> p = new Pair<Runnable, Semaphore>(runnable, new Semaphore(0));\r
+ list.addLast(p);\r
+ notify();\r
+ return this;\r
+ }\r
+\r
+ @Override\r
+ public boolean currentThreadAccess() {\r
+ return Thread.currentThread() == this;\r
+ }\r
+\r
+ @Override\r
+ public Thread getThread() {\r
+ return this;\r
+ }\r
+\r
+}\r