]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.simulator.variable/src/org/simantics/simulator/variable/impl/SimpleRealm.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.simulator.variable / src / org / simantics / simulator / variable / impl / SimpleRealm.java
1 /*******************************************************************************
2  * Copyright (c) 2013 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  *     Semantum Oy - initial API and implementation
12  *******************************************************************************/
13 package org.simantics.simulator.variable.impl;
14
15 import java.util.ArrayDeque;
16 import java.util.concurrent.CountDownLatch;
17 import java.util.concurrent.Semaphore;
18 import java.util.concurrent.TimeUnit;
19
20 import org.simantics.simulator.variable.Realm;
21
22 public class SimpleRealm implements Realm {
23
24         private ArrayDeque<Runnable> tasks = new ArrayDeque<Runnable>();
25         private Semaphore taskCount = new Semaphore(0);
26
27         public void executeTasks() {            
28                 while(taskCount.tryAcquire()) {
29                         Runnable task;
30                         synchronized (tasks) {
31                                 task = tasks.poll();
32                         }
33                         task.run();
34                 }
35         }
36          
37         public void waitTasks(long waitDuration) throws InterruptedException {
38                 taskCount.tryAcquire(waitDuration, TimeUnit.MILLISECONDS);
39         }
40         
41         @Override
42         public void syncExec(final Runnable runnable) throws InterruptedException {
43                 final CountDownLatch latch = new CountDownLatch(1);
44                 asyncExec(new Runnable() {
45                         @Override
46                         public void run() {
47                                 runnable.run();
48                                 latch.countDown();
49                         }                       
50                 });
51                 latch.await();
52         }
53
54         @Override
55         public void asyncExec(Runnable runnable) {
56                 synchronized (tasks) {
57                         tasks.add(runnable);                    
58                 }
59                 taskCount.release();
60         }
61
62 }