1 package org.simantics.db.impl.query;
3 import java.io.BufferedOutputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.PrintStream;
8 import java.util.ArrayList;
9 import java.util.Collection;
10 import java.util.Collections;
11 import java.util.HashMap;
12 import java.util.HashSet;
13 import java.util.LinkedList;
14 import java.util.List;
17 import java.util.concurrent.Semaphore;
18 import java.util.concurrent.ThreadFactory;
19 import java.util.concurrent.atomic.AtomicInteger;
20 import java.util.function.Consumer;
22 import org.simantics.databoard.Bindings;
23 import org.simantics.db.DevelopmentKeys;
24 import org.simantics.db.debug.ListenerReport;
25 import org.simantics.db.exception.DatabaseException;
26 import org.simantics.db.impl.graph.ReadGraphImpl;
27 import org.simantics.db.impl.graph.WriteGraphImpl;
28 import org.simantics.db.procedure.ListenerBase;
29 import org.simantics.utils.Development;
30 import org.simantics.utils.datastructures.Pair;
31 import org.simantics.utils.datastructures.collections.CollectionUtils;
32 import org.slf4j.LoggerFactory;
34 import gnu.trove.map.hash.THashMap;
35 import gnu.trove.set.hash.THashSet;
37 public class QueryListening {
39 private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(QueryListening.class);
41 final private QueryProcessor processor;
42 private THashSet<ListenerEntry> scheduledListeners = new THashSet<ListenerEntry>();
43 private boolean firingListeners = false;
44 final THashMap<CacheEntry, ArrayList<ListenerEntry>> listeners = new THashMap<CacheEntry, ArrayList<ListenerEntry>>(10, 0.75f);
45 private EventBusImpl eventBus;
46 private Consumer<Runnable> consumer;
47 private Map<ListenerBase,ListenerEntry> addedEntries = new HashMap<>();
52 static class TL extends ThreadLocal<ArrayList<Runnable>> {
54 Map<Thread,ArrayList<Runnable>> allQueues = new HashMap<>();
55 ArrayList<ArrayList<Runnable>> dispatchedQueues = new ArrayList<>();
58 protected synchronized ArrayList<Runnable> initialValue() {
59 ArrayList<Runnable> result = new ArrayList<>();
60 allQueues.put(Thread.currentThread(), result);
64 synchronized void sendToExecution() {
65 ArrayList<Runnable> rs = allQueues.remove(Thread.currentThread());
66 dispatchedQueues.add(rs);
70 synchronized ArrayList<ArrayList<Runnable>> getDispatchedQueues() {
71 ArrayList<ArrayList<Runnable>> result = dispatchedQueues;
72 dispatchedQueues = new ArrayList<>();
78 static class EventBusImpl {
80 private static final int BUFFER_SIZE = 100;
83 Semaphore flush = null;
85 public boolean isTerminated() {
89 public Consumer<Runnable> newConsumer() {
90 return new Consumer<Runnable>() {
93 public void accept(Runnable arg0) {
94 ArrayList<Runnable> l = queues.get();
96 if(l.size() == BUFFER_SIZE) {
98 queues.sendToExecution();
104 public void shutdown() {
107 public void start(ThreadFactory arg1) {
108 arg1.newThread(new Runnable() {
112 synchronized(queues) {
113 while(!isTerminated()) {
115 ArrayList<ArrayList<Runnable>> qs = queues.getDispatchedQueues();
116 for(ArrayList<Runnable> queue : qs) {
117 for(Runnable r : queue)
121 for(ArrayList<Runnable> queue : queues.allQueues.values()) {
122 for(Runnable r : queue) {
132 } catch (InterruptedException e) {
143 synchronized(queues) {
144 flush = new Semaphore(0);
149 } catch (InterruptedException e) {
156 QueryListening(QueryProcessor processor) {
157 this.processor = processor;
158 eventBus = new EventBusImpl();
159 consumer = eventBus.newConsumer();
160 eventBus.start(new ThreadFactory()
163 public Thread newThread(Runnable r) {
164 System.err.println("new Thread " + r);
165 return new Thread(r, "QueryDependencyManager");
173 } catch (Throwable t) {
174 LOGGER.error("Error while waiting for query dependency management", t);
178 public boolean hasScheduledUpdates() {
179 return !scheduledListeners.isEmpty();
182 public synchronized void dispatch(Runnable r) {
187 void registerDependencies(ReadGraphImpl graph, CacheEntry child, CacheEntry parent, ListenerBase listener, Object procedure, boolean inferred) {
191 if (parent != null && !inferred) {
193 if(!child.isImmutable(graph))
194 child.addParent(parent);
195 } catch (DatabaseException e) {
196 LOGGER.error("Error while registering query dependencies", e);
198 if (Development.DEVELOPMENT) {
199 if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_DEPENDENCIES, Bindings.BOOLEAN)) {
200 System.out.println(child + " -> " + parent);
205 if (listener != null)
206 registerListener(child, listener, procedure);
212 void registerFirstKnown(ListenerBase base, Object result) {
214 if(base == null) return;
218 ListenerEntry entry = addedEntries.get(base);
219 if(entry != null) entry.setLastKnown(result);
225 public ListenerEntry registerListener(final CacheEntry entry, final ListenerBase base, final Object procedure) {
227 assert (entry != null);
229 if (base.isDisposed())
232 return addListener(entry, base, procedure);
237 * Registers a listener and returns an entry iff the entry was added
239 private ListenerEntry addListener(CacheEntry entry, ListenerBase base, Object procedure) {
241 assert (entry != null);
242 assert (procedure != null);
244 ArrayList<ListenerEntry> list = listeners.get(entry);
246 list = new ArrayList<>(1);
247 listeners.put(entry, list);
250 ListenerEntry result = new ListenerEntry(entry, base, procedure);
251 // Equals is here based on base
252 int currentIndex = list.indexOf(result);
253 // There was already a listener
254 if(currentIndex > -1) {
255 ListenerEntry current = list.get(currentIndex);
256 if(!current.base.isDisposed()) return null;
257 list.set(currentIndex, result);
262 if (Development.DEVELOPMENT) {
263 if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
264 new Exception().printStackTrace();
265 System.err.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure);
269 addedEntries.put(base, result);
275 void scheduleListener(ListenerEntry entry) {
276 assert (entry != null);
277 if (Development.DEVELOPMENT) {
278 if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
279 System.err.println("Scheduled " + entry.procedure);
282 scheduledListeners.add(entry);
285 private void removeListener(ListenerEntry entry) {
286 assert (entry != null);
287 ArrayList<ListenerEntry> list = listeners.get(entry.entry);
288 if(list == null) return;
289 boolean success = list.remove(entry);
292 listeners.remove(entry.entry);
295 boolean hasListener(CacheEntry entry) {
296 if(listeners.get(entry) != null) return true;
300 boolean hasListenerAfterDisposing(CacheEntry entry) {
301 if(listeners.get(entry) != null) {
302 ArrayList<ListenerEntry> entries = listeners.get(entry);
303 ArrayList<ListenerEntry> list = null;
304 for (ListenerEntry e : entries) {
305 if (e.base.isDisposed()) {
306 if(list == null) list = new ArrayList<ListenerEntry>();
311 for (ListenerEntry e : list) {
315 if (entries.isEmpty()) {
316 listeners.remove(entry);
324 List<ListenerEntry> getListenerEntries(CacheEntry entry) {
325 hasListenerAfterDisposing(entry);
326 if(listeners.get(entry) != null)
327 return listeners.get(entry);
329 return Collections.emptyList();
332 void processListenerReport(CacheEntry<?> entry, Map<CacheEntry, Set<ListenerBase>> workarea) {
334 if(!workarea.containsKey(entry)) {
336 HashSet<ListenerBase> ls = new HashSet<ListenerBase>();
337 for(ListenerEntry e : getListenerEntries(entry))
340 workarea.put(entry, ls);
342 for(CacheEntry parent : entry.getParents(processor)) {
343 processListenerReport(parent, workarea);
344 ls.addAll(workarea.get(parent));
351 public synchronized ListenerReport getListenerReport() throws IOException {
353 class ListenerReportImpl implements ListenerReport {
355 Map<CacheEntry, Set<ListenerBase>> workarea = new HashMap<CacheEntry, Set<ListenerBase>>();
358 public void print(PrintStream b) {
359 Map<ListenerBase, Integer> hist = new HashMap<ListenerBase, Integer>();
360 for(Map.Entry<CacheEntry, Set<ListenerBase>> e : workarea.entrySet()) {
361 for(ListenerBase l : e.getValue()) {
362 Integer i = hist.get(l);
363 hist.put(l, i != null ? i-1 : -1);
367 for(Pair<ListenerBase, Integer> p : CollectionUtils.valueSortedEntries(hist)) {
368 b.print("" + -p.second + " " + p.first + "\n");
376 ListenerReportImpl result = new ListenerReportImpl();
378 Collection<CacheEntryBase> all = processor.allCaches(new CacheCollectionResult()).toCollection();
379 for(CacheEntryBase entry : all) {
380 hasListenerAfterDisposing(entry);
382 for(CacheEntryBase entry : all) {
383 processListenerReport(entry, result.workarea);
390 public synchronized String reportListeners(File file) throws IOException {
392 if (!processor.isAlive())
395 PrintStream b = new PrintStream(new BufferedOutputStream(new FileOutputStream(file)));
396 ListenerReport report = getListenerReport();
399 return "Done reporting listeners.";
403 public void fireListeners(WriteGraphImpl graph) {
405 assert (!processor.updating);
406 assert (!processor.cache.collecting);
407 assert (!firingListeners);
409 firingListeners = true;
413 // Performing may cause further events to be scheduled.
414 while (!scheduledListeners.isEmpty()) {
416 // Clone current events to make new entries possible during
418 THashSet<ListenerEntry> entries = scheduledListeners;
419 scheduledListeners = new THashSet<ListenerEntry>();
421 ArrayList<ListenerEntry> schedule = new ArrayList<ListenerEntry>();
423 for (ListenerEntry listenerEntry : entries) {
425 if (pruneListener(listenerEntry)) {
426 if (Development.DEVELOPMENT) {
427 if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
428 new Exception().printStackTrace();
429 System.err.println("Pruned " + listenerEntry.procedure);
435 final CacheEntry entry = listenerEntry.entry;
436 assert (entry != null);
438 Object newValue = processor.compareTo(graph, entry, listenerEntry.getLastKnown());
440 if (newValue != ListenerEntry.NOT_CHANGED) {
441 if (Development.DEVELOPMENT) {
442 if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
443 new Exception().printStackTrace();
444 System.err.println("Add to schedule " + listenerEntry.procedure + " with " + newValue);
447 schedule.add(listenerEntry);
448 listenerEntry.setLastKnown(entry.getResult());
453 for(ListenerEntry listenerEntry : schedule) {
454 final CacheEntry entry = listenerEntry.entry;
455 if (Development.DEVELOPMENT) {
456 if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
457 System.err.println("Firing " + listenerEntry.procedure);
461 if (Development.DEVELOPMENT) {
462 if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
463 System.err.println("Firing " + listenerEntry.procedure + " for " + listenerEntry.entry);
466 entry.performFromCache(graph, listenerEntry.procedure);
467 } catch (Throwable t) {
475 firingListeners = false;
480 void updateParents(int indent, CacheEntry entry, LinkedList<UpdateEntry> todo) {
482 Iterable<CacheEntry> oldParents = entry.getParents(processor);
483 for (CacheEntry parent : oldParents) {
484 if(!parent.isDiscarded())
485 todo.push(new UpdateEntry(entry, parent, indent + 2));
490 private boolean pruneListener(ListenerEntry entry) {
491 if (entry.base.isDisposed()) {
492 removeListener(entry);