]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.utils.thread/src/org/simantics/utils/threads/ua/SerialExecutor.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.utils.thread / src / org / simantics / utils / threads / ua / SerialExecutor.java
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 \r
13 package org.simantics.utils.threads.ua;\r
14 \r
15 import java.util.ArrayDeque;\r
16 import java.util.Queue;\r
17 import java.util.concurrent.Executor;\r
18 \r
19 /**\r
20  * The executor serializes the submission of tasks to a second executor,\r
21  * illustrating a composite executor.\r
22  * \r
23  * (This code is copied from the example in {@link Executor})\r
24  */\r
25 public class SerialExecutor implements Executor {\r
26     final Queue<Runnable> tasks = new ArrayDeque<Runnable>();\r
27     final Executor executor;\r
28     Runnable active;\r
29                  \r
30     public SerialExecutor(Executor executor) {\r
31         this.executor = executor;\r
32     }\r
33                  \r
34     public synchronized void execute(final Runnable r) {\r
35         tasks.offer(new Runnable() {\r
36             public void run() {\r
37                 try {\r
38                     r.run();\r
39                 } finally {\r
40                     scheduleNext();\r
41                 }\r
42             }\r
43         });\r
44         if (active == null) {\r
45             scheduleNext();\r
46         }\r
47     }\r
48                  \r
49     protected synchronized void scheduleNext() {\r
50         if ((active = tasks.poll()) != null) {\r
51             executor.execute(active);\r
52         }\r
53     }\r
54         \r
55 }\r