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