1 package org.simantics.modeling.scl;
3 import java.io.IOException;
6 import java.util.concurrent.LinkedBlockingQueue;
7 import java.util.concurrent.Semaphore;
8 import java.util.concurrent.ThreadFactory;
9 import java.util.concurrent.ThreadPoolExecutor;
10 import java.util.concurrent.TimeUnit;
12 import org.simantics.databoard.Bindings;
13 import org.simantics.databoard.binding.Binding;
14 import org.simantics.databoard.binding.mutable.Variant;
15 import org.simantics.databoard.serialization.RuntimeSerializerConstructionException;
16 import org.simantics.modeling.SCLTypeUtils;
17 import org.simantics.scl.compiler.commands.CommandSession;
18 import org.simantics.scl.compiler.types.Type;
19 import org.simantics.scl.runtime.SCLContext;
20 import org.simantics.scl.runtime.function.Function;
21 import org.simantics.scl.runtime.tuple.Tuple0;
22 import org.simantics.simulator.variable.Realm;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
26 import gnu.trove.map.hash.THashMap;
28 public class SCLRealm implements Realm {
29 private static final Logger LOGGER = LoggerFactory.getLogger(SCLRealm.class);
31 public static final String SCL = "scl";
33 private THashMap<String,Type> contextTypes = new THashMap<String,Type>();
35 private CommandSession connection;
37 private Thread executorThread;
38 private SCLRealmThreadFactory factory = new SCLRealmThreadFactory(this);
39 private ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS,
40 new LinkedBlockingQueue<Runnable>(), factory);
42 private Semaphore beginSyncExec = new Semaphore(0);
43 private Semaphore endSyncExec = new Semaphore(0);
45 private SCLNodeManager nodeManager;
47 private Runnable scheduleSyncExec = new Runnable() {
50 beginSyncExec.release();
52 endSyncExec.acquire();
53 } catch (InterruptedException e) {
58 SCLRealm(CommandSession connection, String id) {
59 this.connection = connection;
61 this.nodeManager = new SCLNodeManager(this);
64 public String getId() {
68 public CommandSession getConnection() {
72 public Thread getThread() {
73 return executorThread;
76 @SuppressWarnings({ "rawtypes", "unchecked" })
77 public Object syncExec(Function fun) throws InterruptedException {
78 executor.execute(scheduleSyncExec);
80 SCLContext context = SCLContext.getCurrent();
81 CommandSession oldConnection = (CommandSession)context.put(SCL, connection);
84 beginSyncExec.acquire();
85 Thread oldThread = executorThread;
86 executorThread = Thread.currentThread();
88 return fun.apply(Tuple0.INSTANCE);
90 executorThread = oldThread;
91 endSyncExec.release();
94 context.put(SCL, oldConnection);
98 @SuppressWarnings("rawtypes")
99 public void asyncExec(final Function fun) {
100 executor.execute(new Runnable() {
101 @SuppressWarnings("unchecked")
104 SCLContext context = SCLContext.getCurrent();
105 context.put(SCL, connection);
106 fun.apply(Tuple0.INSTANCE);
112 public void syncExec(Runnable runnable) throws InterruptedException {
114 if(executorThread == Thread.currentThread()) {
117 } catch (Throwable t) {
118 LOGGER.error("Runnable failed in syncExec.", t);
124 executor.execute(scheduleSyncExec);
126 beginSyncExec.acquire();
127 Thread oldThread = executorThread;
128 executorThread = Thread.currentThread();
131 } catch (Throwable t) {
132 LOGGER.error("Runnable failed in syncExec.", t);
134 executorThread = oldThread;
135 endSyncExec.release();
140 public void asyncExec(Runnable runnable) {
142 if(executorThread == Thread.currentThread()) {
145 } catch (Throwable t) {
146 LOGGER.error("Runnable failed in asyncExec.", t);
152 executor.execute(runnable);
155 public void refreshVariables() {
156 nodeManager.refreshVariables();
159 public void refreshVariablesSync() {
160 nodeManager.refreshVariablesSync();
163 public void close() {
164 SCLSessionManager.CONNECTIONS.remove(id);
167 if (!executor.awaitTermination(500L, TimeUnit.MILLISECONDS)) {
168 List<Runnable> runnables = executor.shutdownNow();
169 if (!runnables.isEmpty()) {
170 LOGGER.info("Some runnables left to execute in realm " + this + ": " + runnables);
173 } catch (InterruptedException e) {
174 LOGGER.info("Could not shutdown executor " + executor + " in realm " + this, e);
176 //connection.close();
181 if (executorThread.isAlive())
182 executorThread.interrupt();
183 executorThread = null;
190 public SCLNodeManager getNodeManager() {
194 private SCLState getState() {
195 SCLState state = new SCLState();
196 for(String key : connection.getVariables()) {
197 Object value = connection.getVariableValue(key);
199 Binding b = Bindings.getBinding(value.getClass());
200 state.values.put(key, new Variant(b, value));
201 } catch (Exception e) {
207 public void applyState(byte[] blob) {
209 SCLState state = (SCLState)SCLState.BINDING.serializer().deserialize(blob);
210 for(Map.Entry<String,Variant> entry : state.values.entrySet()) {
211 String key = entry.getKey();
212 Variant value = entry.getValue();
213 Type type = SCLTypeUtils.getType(value.type());
214 if (type.getClassId() != Type.VAR_ID) {
215 // do not add the property if type cannot be inferred
216 connection.setVariable(key, type, value.getValue());
219 } catch (RuntimeSerializerConstructionException e) {
220 } catch (IOException e) {
224 public byte[] serialize() {
225 SCLState state = getState();
227 return SCLState.BINDING.serializer().serialize(state);
228 } catch (RuntimeSerializerConstructionException e) {
230 } catch (IOException e) {
235 private static class SCLRealmThreadFactory implements ThreadFactory {
237 private SCLRealm realm;
239 public SCLRealmThreadFactory(SCLRealm realm) {
244 public Thread newThread(Runnable r) {
245 Thread t = new Thread(r);
255 private void setThread(Thread t) {
256 this.executorThread = t;