/******************************************************************************* * Copyright (c) 2013 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation * Semantum Oy - initial API and implementation *******************************************************************************/ package org.simantics.simulator.variable.impl; import java.util.ArrayDeque; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.simantics.simulator.variable.Realm; public class SimpleRealm implements Realm { private ArrayDeque tasks = new ArrayDeque(); private Semaphore taskCount = new Semaphore(0); public void executeTasks() { while(taskCount.tryAcquire()) { Runnable task; synchronized (tasks) { task = tasks.poll(); } task.run(); } } public void waitTasks(long waitDuration) throws InterruptedException { taskCount.tryAcquire(waitDuration, TimeUnit.MILLISECONDS); } @Override public void syncExec(final Runnable runnable) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); asyncExec(new Runnable() { @Override public void run() { runnable.run(); latch.countDown(); } }); latch.await(); } @Override public void asyncExec(Runnable runnable) { synchronized (tasks) { tasks.add(runnable); } taskCount.release(); } }