1 package org.simantics.db.impl.query;
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.LinkedList;
7 import java.util.concurrent.Semaphore;
9 import org.simantics.db.impl.graph.BarrierTracing;
10 import org.simantics.db.impl.graph.ReadGraphImpl;
11 import org.simantics.db.impl.query.QueryProcessor.AsyncBarrier;
12 import org.simantics.db.impl.query.QueryProcessor.SessionTask;
14 public class Scheduling {
16 private final Semaphore requests;
18 private Map<AsyncBarrier, LinkedList<SessionTask>> freeScheduling = new HashMap<>();
20 private LinkedList<SessionTask> topLevelTasks = new LinkedList<SessionTask>();
22 public Scheduling(Semaphore requests) {
23 this.requests = requests;
26 public SessionTask getSubTask(ReadGraphImpl parent) {
28 assert(parent.asyncBarrier.isBlocking());
29 LinkedList<SessionTask> tasks = freeScheduling.get(parent.asyncBarrier);
32 SessionTask task = tasks.removeLast();
34 freeScheduling.remove(parent.asyncBarrier);
39 public boolean pumpTask(ArrayList<SessionTask> tasks) {
43 // First finish existing executions
44 if(!freeScheduling.isEmpty()) {
45 Map.Entry<AsyncBarrier, LinkedList<SessionTask>> ls = freeScheduling.entrySet().iterator().next();
46 assert(ls.getKey().isBlocking());
47 tasks.add(ls.getValue().removeLast());
48 if(ls.getValue().isEmpty())
49 freeScheduling.remove(ls.getKey());
52 // Check for new tasks
53 if(!topLevelTasks.isEmpty()) {
54 tasks.add(topLevelTasks.removeLast());
64 final public SessionTask scheduleOrReturnForExecution(SessionTask request) {
66 assert(request != null);
70 if(BarrierTracing.BOOKKEEPING) {
71 Exception current = new Exception();
72 Exception previous = BarrierTracing.tasks.put(request, current);
73 if(previous != null) {
74 previous.printStackTrace();
75 current.printStackTrace();
81 if(request.rootGraph != null) {
82 AsyncBarrier sb = request.rootGraph.asyncBarrier.getBlockingBarrier();
84 LinkedList<SessionTask> ls = freeScheduling.get(sb);
86 ls = new LinkedList<SessionTask>();
87 freeScheduling.put(sb, ls);
94 topLevelTasks.addFirst(request);