aboutsummaryrefslogtreecommitdiffstats
path: root/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java
diff options
context:
space:
mode:
Diffstat (limited to 'Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java')
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java374
1 files changed, 374 insertions, 0 deletions
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java
new file mode 100644
index 00000000..7325ead3
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java
@@ -0,0 +1,374 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2014, Miklos Foldenyi, Andras Szabolcs Nagy, Abel Hegedus, Akos Horvath, Zoltan Ujhelyi and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import java.util.ArrayList;
12import java.util.Collection;
13import java.util.HashMap;
14import java.util.HashSet;
15import java.util.List;
16import java.util.Map;
17import java.util.Set;
18import java.util.concurrent.ConcurrentLinkedQueue;
19import java.util.concurrent.atomic.AtomicBoolean;
20
21import org.apache.log4j.Logger;
22import org.eclipse.emf.common.notify.Notifier;
23import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy;
24import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategyFactory;
25import org.eclipse.viatra.dse.designspace.api.IDesignSpace;
26import org.eclipse.viatra.dse.multithreading.DSEThreadPool;
27import org.eclipse.viatra.dse.objectives.IGlobalConstraint;
28import org.eclipse.viatra.dse.objectives.IObjective;
29import org.eclipse.viatra.dse.objectives.LeveledObjectivesHelper;
30import org.eclipse.viatra.dse.solutionstore.SolutionStore;
31import org.eclipse.viatra.dse.statecode.IStateCoderFactory;
32import org.eclipse.viatra.dse.util.EMFHelper;
33import org.eclipse.viatra.dse.visualizer.IDesignSpaceVisualizer;
34import org.eclipse.viatra.transformation.evm.api.RuleSpecification;
35import org.eclipse.viatra.transformation.evm.api.resolver.ConflictResolver;
36import org.eclipse.viatra.transformation.evm.specific.ConflictResolvers;
37import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule;
38
39import com.google.common.base.Preconditions;
40import com.google.common.collect.ImmutableList;
41
42/**
43 * Creates new contexts for strategies. It is needed because of the multithreading.
44 *
45 * @author Andras Szabolcs Nagy
46 *
47 */
48public class GlobalContext {
49
50 // **** fields and methods for multi threading *****//
51 // *************************************************//
52
53 public enum ExplorationProcessState {
54 NOT_STARTED,
55 RUNNING,
56 STOPPING,
57 COMPLETED
58 }
59
60 private ConcurrentLinkedQueue<Throwable> exceptions = new ConcurrentLinkedQueue<Throwable>();
61
62 private volatile ExplorationProcessState state = ExplorationProcessState.NOT_STARTED;
63 private final Set<ExplorerThread> runningThreads = new HashSet<ExplorerThread>();
64 private DSEThreadPool threadPool = new DSEThreadPool();
65 private int numberOfStartedThreads = 0;
66 private IDesignSpace designSpace;
67
68 private AtomicBoolean firstThreadContextInited = new AtomicBoolean(false);
69 private AtomicBoolean firstThreadContextIniting = new AtomicBoolean(false);
70
71 private Map<RuleSpecification<?>, BatchTransformationRule<?,?>> specificationRuleMap;
72
73 private Object terminationSnycObject = new Object();
74
75 private Logger logger = Logger.getLogger(IStrategy.class);
76
77 private boolean isAlreadyInited;
78
79 public void waitForTermination() {
80 synchronized (terminationSnycObject) {
81 while (!isDone()) {
82 try {
83 terminationSnycObject.wait();
84 } catch (InterruptedException e) {
85 }
86 }
87 }
88 }
89
90 /**
91 * Starts a new thread to explore the design space.
92 *
93 * @param originalThreadContext The context of the thread which starts the new thread.
94 * @param model The model to start from.
95 * @param cloneModel It should be true in most cases.
96 * @param strategy The strategy, the thread will use.
97 * @return The {@link ExplorerThread}
98 */
99 private synchronized ExplorerThread tryStartNewThread(ThreadContext originalThreadContext, Notifier model,
100 IStrategy strategy) {
101
102 if(!isAlreadyInited) {
103 isAlreadyInited = true;
104 init();
105 }
106
107 if (state != ExplorationProcessState.COMPLETED && state != ExplorationProcessState.STOPPING
108 && threadPool.canStartNewThread()) {
109
110 ThreadContext newThreadContext = new ThreadContext(this, strategy, model);
111
112 // TODO : clone undo list? slave strategy can't go further back...
113 ExplorerThread explorerThread = new ExplorerThread(newThreadContext);
114 newThreadContext.setExplorerThread(explorerThread);
115
116 boolean isSuccessful = threadPool.tryStartNewStrategy(explorerThread);
117
118 if (isSuccessful) {
119 runningThreads.add(explorerThread);
120
121 state = ExplorationProcessState.RUNNING;
122 ++numberOfStartedThreads;
123
124 logger.info("New thread started, active threads: " + runningThreads.size());
125
126 return explorerThread;
127 }
128 }
129 return null;
130 }
131
132 public synchronized ExplorerThread tryStartNewThread(ThreadContext originalThreadContext, IStrategy strategy) {
133 return tryStartNewThread(originalThreadContext, EMFHelper.clone(originalThreadContext.getModel()), strategy);
134 }
135
136 public synchronized ExplorerThread tryStartNewThreadWithoutModelClone(ThreadContext originalThreadContext,
137 IStrategy strategy) {
138 return tryStartNewThread(originalThreadContext, originalThreadContext.getModel(), strategy);
139 }
140
141 public synchronized ExplorerThread startFirstThread(IStrategy strategy, Notifier model) {
142 Preconditions.checkState(!isAlreadyInited, "First thread is already started.");
143 return tryStartNewThread(null, EMFHelper.clone(model), strategy);
144 }
145
146 public synchronized ExplorerThread startFirstThreadWithoutModelClone(IStrategy strategy, Notifier model) {
147 Preconditions.checkState(!isAlreadyInited, "First thread is already started.");
148 return tryStartNewThread(null, model, strategy);
149 }
150
151 public synchronized void startAllThreads(ThreadContext originalThreadContext, IStrategyFactory strategyFactory) {
152 while (canStartNewThread()) {
153 tryStartNewThread(originalThreadContext, strategyFactory.createStrategy());
154 }
155 }
156
157 /**
158 * Starts a new thread to explore the design space.
159 *
160 * @param strategyBase
161 * The {@link Strategy}.
162 * @param tedToClone
163 * The model to clone. Hint: context.getTed()
164 */
165
166 public synchronized void strategyFinished(ExplorerThread strategy) {
167 runningThreads.remove(strategy);
168
169 logger.info("Thread finished, active threads: " + runningThreads.size());
170
171 // is the first part necessary?
172 if (runningThreads.isEmpty()) {
173 state = ExplorationProcessState.COMPLETED;
174 threadPool.shutdown();
175
176 // if the main thread (which started the exploration)
177 // is waiting for the solution, than wake it up
178 synchronized (terminationSnycObject) {
179 terminationSnycObject.notify();
180 logger.info("Exploration terminated.");
181 }
182
183 }
184 }
185
186 public synchronized boolean isDone() {
187 return state == ExplorationProcessState.COMPLETED && runningThreads.isEmpty();
188 }
189
190 public synchronized boolean isNotStarted() {
191 return state == ExplorationProcessState.NOT_STARTED;
192 }
193
194 public boolean canStartNewThread() {
195 return (state == ExplorationProcessState.NOT_STARTED || state == ExplorationProcessState.RUNNING)
196 && threadPool.canStartNewThread();
197 }
198
199 public synchronized void stopAllThreads() {
200 if (state == ExplorationProcessState.RUNNING) {
201 state = ExplorationProcessState.STOPPING;
202 logger.info("Stopping all threads.");
203 for (ExplorerThread strategy : runningThreads) {
204 strategy.stopRunning();
205 }
206 }
207 }
208
209 public void registerException(Throwable e) {
210 exceptions.add(e);
211 }
212
213 // ******* fields and methods for exploration *******//
214 // **************************************************//
215
216 private List<IObjective> objectives = new ArrayList<IObjective>();
217 private IObjective[][] leveledObjectives;
218 private List<IGlobalConstraint> globalConstraints = new ArrayList<IGlobalConstraint>();
219 private Set<BatchTransformationRule<?, ?>> transformations = new HashSet<BatchTransformationRule<?, ?>>();
220 private IStateCoderFactory stateCoderFactory;
221 private SolutionStore solutionStore = new SolutionStore(1);
222 private Object sharedObject;
223 private List<IDesignSpaceVisualizer> visualizers;
224
225 private ConflictResolver conflictResolver = ConflictResolvers.createArbitraryResolver();
226
227 private void init() {
228 leveledObjectives = new LeveledObjectivesHelper(objectives).initLeveledObjectives();
229
230 specificationRuleMap = new HashMap<>();
231 for (BatchTransformationRule<?,?> rule : transformations) {
232 specificationRuleMap.put(rule.getRuleSpecification(), rule);
233 }
234 }
235
236 public List<IDesignSpaceVisualizer> getVisualizers() {
237 return ImmutableList.copyOf(visualizers);
238 }
239
240 public void registerDesignSpaceVisualizer(IDesignSpaceVisualizer visualizer) {
241 if (visualizer == null) {
242 return;
243 }
244 if (visualizers == null) {
245 visualizers = new ArrayList<IDesignSpaceVisualizer>();
246 }
247 visualizers.add(visualizer);
248 }
249
250 public void deregisterDesignSpaceVisualizer(IDesignSpaceVisualizer visualizer) {
251 if (visualizer == null) {
252 return;
253 }
254 if (visualizers != null) {
255 visualizers.remove(visualizer);
256 }
257 }
258
259 public boolean isDesignSpaceVisualizerRegistered(IDesignSpaceVisualizer visualizer) {
260 if (visualizers != null) {
261 return visualizers.contains(visualizer);
262 }
263 return false;
264 }
265
266 public void initVisualizersForThread(ThreadContext threadContext) {
267 if (visualizers != null && !visualizers.isEmpty()) {
268 for (IDesignSpaceVisualizer visualizer : visualizers) {
269 visualizer.init(threadContext);
270 threadContext.getDesignSpaceManager().registerExploreEventHandler(visualizer);
271 }
272 }
273 }
274
275 public boolean isExceptionHappendInOtherThread() {
276 return !exceptions.isEmpty();
277 }
278
279 public Collection<Throwable> getExceptions() {
280 return exceptions;
281 }
282
283 public IStateCoderFactory getStateCoderFactory() {
284 return stateCoderFactory;
285 }
286
287 public void setStateCoderFactory(IStateCoderFactory stateCoderFactory) {
288 this.stateCoderFactory = stateCoderFactory;
289 }
290
291 public Set<BatchTransformationRule<?, ?>> getTransformations() {
292 return transformations;
293 }
294
295 public void setTransformations(Set<BatchTransformationRule<?, ?>> transformations) {
296 this.transformations = transformations;
297 }
298
299 public DSEThreadPool getThreadPool() {
300 return threadPool;
301 }
302
303 public IDesignSpace getDesignSpace() {
304 return designSpace;
305 }
306
307 public void setDesignSpace(IDesignSpace designSpace) {
308 this.designSpace = designSpace;
309 }
310
311 public int getNumberOfStartedThreads() {
312 return numberOfStartedThreads;
313 }
314
315 public Object getSharedObject() {
316 return sharedObject;
317 }
318
319 public void setSharedObject(Object sharedObject) {
320 this.sharedObject = sharedObject;
321 }
322
323 public ExplorationProcessState getState() {
324 return state;
325 }
326
327 public List<IObjective> getObjectives() {
328 return objectives;
329 }
330
331 public void setObjectives(List<IObjective> objectives) {
332 this.objectives = objectives;
333 }
334
335 public List<IGlobalConstraint> getGlobalConstraints() {
336 return globalConstraints;
337 }
338
339 public void setGlobalConstraints(List<IGlobalConstraint> globalConstraints) {
340 this.globalConstraints = globalConstraints;
341 }
342
343 AtomicBoolean getFirstThreadContextInited() {
344 return firstThreadContextInited;
345 }
346
347 AtomicBoolean getFirstThreadContextIniting() {
348 return firstThreadContextIniting;
349 }
350
351 public IObjective[][] getLeveledObjectives() {
352 return leveledObjectives;
353 }
354
355 public void setSolutionStore(SolutionStore solutionStore) {
356 this.solutionStore = solutionStore;
357 }
358
359 public SolutionStore getSolutionStore() {
360 return solutionStore;
361 }
362
363 public Map<RuleSpecification<?>, BatchTransformationRule<?, ?>> getSpecificationRuleMap() {
364 return specificationRuleMap;
365 }
366
367 public void setConflictResolver(ConflictResolver conflictResolver) {
368 this.conflictResolver = conflictResolver;
369 }
370
371 public ConflictResolver getConflictResolver() {
372 return conflictResolver;
373 }
374}