X-Git-Url: https://gerrit.simantics.org/r/gitweb?p=simantics%2Fplatform.git;a=blobdiff_plain;f=bundles%2Forg.simantics.db.impl%2Fsrc%2Forg%2Fsimantics%2Fdb%2Fimpl%2Fquery%2FQueryProcessor.java;h=55855ee3e823bed936c00c558848ceaf05a04915;hp=ff15d301b58214a25d20bb663889d11430008ae2;hb=cb12888f3415720276da57f2d162e13ea5b3f46c;hpb=0ae2b770234dfc3cbb18bd38f324125cf0faca07 diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryProcessor.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryProcessor.java index ff15d301b..55855ee3e 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryProcessor.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryProcessor.java @@ -31,8 +31,6 @@ import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.ReentrantLock; import org.simantics.databoard.Bindings; import org.simantics.db.AsyncReadGraph; @@ -51,9 +49,8 @@ import org.simantics.db.exception.DatabaseException; import org.simantics.db.exception.ManyObjectsForFunctionalRelationException; import org.simantics.db.exception.NoInverseException; import org.simantics.db.exception.ResourceNotFoundException; -import org.simantics.db.impl.DebugPolicy; import org.simantics.db.impl.ResourceImpl; -import org.simantics.db.impl.graph.MultiIntProcedure; +import org.simantics.db.impl.graph.BarrierTracing; import org.simantics.db.impl.graph.ReadGraphImpl; import org.simantics.db.impl.graph.ReadGraphSupport; import org.simantics.db.impl.graph.WriteGraphImpl; @@ -65,18 +62,14 @@ import org.simantics.db.procedure.AsyncMultiListener; import org.simantics.db.procedure.AsyncMultiProcedure; import org.simantics.db.procedure.AsyncProcedure; import org.simantics.db.procedure.AsyncSetListener; -import org.simantics.db.procedure.Listener; import org.simantics.db.procedure.ListenerBase; import org.simantics.db.procedure.MultiProcedure; -import org.simantics.db.procedure.Procedure; import org.simantics.db.procedure.StatementProcedure; +import org.simantics.db.procedure.SyncMultiProcedure; import org.simantics.db.request.AsyncMultiRead; -import org.simantics.db.request.AsyncRead; import org.simantics.db.request.ExternalRead; import org.simantics.db.request.MultiRead; -import org.simantics.db.request.Read; import org.simantics.db.request.RequestFlags; -import org.simantics.db.request.WriteTraits; import org.simantics.layer0.Layer0; import org.simantics.utils.DataContainer; import org.simantics.utils.Development; @@ -84,7 +77,6 @@ import org.simantics.utils.datastructures.Pair; import org.simantics.utils.datastructures.collections.CollectionUtils; import org.simantics.utils.datastructures.disposable.AbstractDisposable; -import gnu.trove.map.hash.THashMap; import gnu.trove.procedure.TIntProcedure; import gnu.trove.procedure.TLongProcedure; import gnu.trove.procedure.TObjectProcedure; @@ -94,47 +86,13 @@ import gnu.trove.set.hash.TIntHashSet; @SuppressWarnings({"rawtypes", "unchecked"}) final public class QueryProcessor extends AbstractDisposable implements ReadGraphSupport { - final public UnaryQueryHashMap directPredicatesMap; - final public UnaryQueryHashMap principalTypesMap; - final public THashMap uriToResourceMap; - final public THashMap namespaceIndexMap22; - final public UnaryQueryHashMap projectsMap; - final public UnaryQueryHashMap> relationInfoMap; - final public UnaryQueryHashMap> superTypesMap; - final public UnaryQueryHashMap> typeHierarchyMap; - final public UnaryQueryHashMap> superRelationsMap; - final public UnaryQueryHashMap> typesMap; - final public UnaryQueryHashMap> valueMap; - final public DoubleKeyQueryHashMap directObjectsMap; - final public DoubleKeyQueryHashMap objectsMap; - final public UnaryQueryHashMap orderedSetMap; - final public UnaryQueryHashMap predicatesMap; - final public DoubleKeyQueryHashMap statementsMap; - final public UnaryQueryHashMap assertedPredicatesMap; - final public BinaryQueryHashMap assertedStatementsMap; - final public StableHashMap externalReadMap; - final public StableHashMap asyncReadMap; - final public StableHashMap readMap; - final public StableHashMap asyncMultiReadMap; - final public StableHashMap multiReadMap; - - final private THashMap> listeners; - public static int indent = 0; - public int size = 0; - // Garbage collection public int boundQueries = 0; - // Statistics - private int hits = 0; - - private int misses = 0; - - private int updates = 0; final private int functionalRelation; @@ -174,10 +132,10 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap private boolean updating = false; - static public boolean collecting = false; private boolean firingListeners = false; + final public QueryCache cache; final public QuerySupport querySupport; final public Session session; final public ResourceSupport resourceSupport; @@ -186,7 +144,9 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap QueryThread[] executors; - public ArrayList[] queues; +// public ArrayList[] queues; + + public LinkedList freeScheduling = new LinkedList(); enum ThreadState { @@ -195,17 +155,15 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } public ThreadState[] threadStates; - public ReentrantLock[] threadLocks; - public Condition[] threadConditions; +// public ReentrantLock[] threadLocks; +// public Condition[] threadConditions; - public ArrayList[] ownTasks; + //public ArrayList[] ownTasks; - public ArrayList[] ownSyncTasks; + //public ArrayList[] ownSyncTasks; - ArrayList[] delayQueues; + //ArrayList[] delayQueues; - public boolean synch = true; - final Object querySupportLock; public Long modificationCounter = 0L; @@ -213,77 +171,145 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap public void close() { } - final public void scheduleOwn(int caller, SessionTask request) { - ownTasks[caller].add(request); + public SessionTask getOwnTask(ReadGraphImpl impl) { + Set ancestors = impl.ancestorSet(); + synchronized(querySupportLock) { + int index = 0; + while(index < freeScheduling.size()) { + SessionTask task = freeScheduling.get(index); + if(task.hasCommonParent(ancestors)) { + return freeScheduling.remove(index); + } + index++; + } + } + return null; } - final public void scheduleAlways(int caller, SessionTask request) { + public SessionTask getSubTask(ReadGraphImpl impl) { + Set onlyThis = Collections.singleton(impl); + synchronized(querySupportLock) { + int index = 0; + while(index < freeScheduling.size()) { + SessionTask task = freeScheduling.get(index); + if(task.hasCommonParent(onlyThis)) { + return freeScheduling.remove(index); + } + index++; + } + } + return null; + } - int performer = request.thread; - if(caller == performer) { - ownTasks[caller].add(request); + public boolean performPending(ReadGraphImpl graph) { + SessionTask task = getOwnTask(graph); + if(task != null) { + task.run(QueryProcessor.thread.get()); + return true; } else { - schedule(caller, request); + return false; } - } - final public void schedule(int caller, SessionTask request) { +// final public void scheduleOwn(int caller, SessionTask request) { +// ownTasks[caller].add(request); +// } - int performer = request.thread; + final public void schedule(SessionTask request) { + + //int performer = request.thread; - if(DebugPolicy.SCHEDULE) - System.out.println("schedule " + request + " " + caller + " -> " + performer); +// if(DebugPolicy.SCHEDULE) +// System.out.println("schedule " + request + " " + " -> " + performer); - assert(performer >= 0); + //assert(performer >= 0); assert(request != null); - if(caller == performer) { - request.run(caller); - } else { - ReentrantLock queueLock = threadLocks[performer]; - queueLock.lock(); - queues[performer].add(request); - // This thread could have been sleeping - if(queues[performer].size() == 1) { - if(ThreadState.SLEEP == threadStates[performer]) sleepers.decrementAndGet(); - threadConditions[performer].signalAll(); - } - queueLock.unlock(); - } +// if(caller == performer) { +// request.run(caller); +// } else { + +// if(performer == THREADS) { + + synchronized(querySupportLock) { + + if(BarrierTracing.BOOKKEEPING) { + Exception current = new Exception(); + Exception previous = BarrierTracing.tasks.put(request, current); + if(previous != null) { + previous.printStackTrace(); + current.printStackTrace(); + } + } + + freeScheduling.add(request); + + querySupportLock.notifyAll(); + + } + + return; + +// } +// +// ReentrantLock queueLock = threadLocks[performer]; +// queueLock.lock(); +// queues[performer].add(request); +// // This thread could have been sleeping +// if(queues[performer].size() == 1) { +// //if(ThreadState.SLEEP == threadStates[performer]) sleepers.decrementAndGet(); +// threadConditions[performer].signalAll(); +// } +// queueLock.unlock(); +// } } final int THREADS; - final public int THREAD_MASK; - final public static ThreadGroup QueryThreadGroup = new ThreadGroup("Query Thread Group"); + + final public static ThreadGroup QueryThreadGroup = new ThreadGroup("Query Thread Group"); public static abstract class SessionTask { - final public int thread; - final public int syncCaller; - final public Object object; + public final ReadGraphImpl graph; + private Set ancestors; + private int counter = 0; + private Exception trace; - public SessionTask(WriteTraits object, int thread) { - this.thread = thread; - this.syncCaller = -1; - this.object = object; + public SessionTask(ReadGraphImpl graph) { + this.graph = graph; + if(graph != null) graph.asyncBarrier.inc(); } - public SessionTask(Object object, int thread, int syncCaller) { - this.thread = thread; - this.syncCaller = syncCaller; - this.object = object; + public boolean hasCommonParent(Set otherAncestors) { + if(graph == null) return false; + if(ancestors == null) ancestors = graph.ancestorSet(); + return !Collections.disjoint(ancestors, otherAncestors); } - public abstract void run(int thread); + public abstract void run0(int thread); + + public final void run(int thread) { + if(counter++ > 0) { + if(BarrierTracing.BOOKKEEPING) { + trace.printStackTrace(); + new Exception().printStackTrace(); + } + throw new IllegalStateException("Multiple invocations of SessionTask!"); + } + if(BarrierTracing.BOOKKEEPING) { + trace = new Exception(); + } + run0(thread); + if(graph != null) graph.asyncBarrier.dec(); + } @Override public String toString() { - return "SessionTask[" + object + "]"; + return "SessionTask[" + graph.parent + "]"; } } @@ -293,14 +319,8 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap final public Semaphore notify; final public DataContainer throwable; - public SessionRead(Object object, DataContainer throwable, Semaphore notify, int thread) { - super(object, thread, thread); - this.throwable = throwable; - this.notify = notify; - } - - public SessionRead(Object object, DataContainer throwable, Semaphore notify, int thread, int syncThread) { - super(object, thread, syncThread); + public SessionRead(DataContainer throwable, Semaphore notify) { + super(null); this.throwable = throwable; this.notify = notify; } @@ -315,41 +335,61 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap public boolean resume(ReadGraphImpl graph) { return executors[0].runSynchronized(); } + + //private WeakReference garbageTracker; + + private class GarbageTracker { + + @Override + protected void finalize() throws Throwable { + +// System.err.println("GarbageTracker"); +// +// garbageTracker = new WeakReference(new GarbageTracker()); + + super.finalize(); + + } + + } public QueryProcessor(final int threads, QuerySupport core, Set threadSet) throws DatabaseException { + //garbageTracker = new WeakReference(new GarbageTracker()); + THREADS = threads; THREAD_MASK = threads - 1; querySupport = core; + cache = new QueryCache(core, threads); session = querySupport.getSession(); resourceSupport = querySupport.getSupport(); querySupportLock = core.getLock(); executors = new QueryThread[THREADS]; - queues = new ArrayList[THREADS]; - threadLocks = new ReentrantLock[THREADS]; - threadConditions = new Condition[THREADS]; +// queues = new ArrayList[THREADS]; +// threadLocks = new ReentrantLock[THREADS]; +// threadConditions = new Condition[THREADS]; threadStates = new ThreadState[THREADS]; - ownTasks = new ArrayList[THREADS]; - ownSyncTasks = new ArrayList[THREADS]; - delayQueues = new ArrayList[THREADS * THREADS]; +// ownTasks = new ArrayList[THREADS]; +// ownSyncTasks = new ArrayList[THREADS]; +// delayQueues = new ArrayList[THREADS * THREADS]; // freeSchedule = new AtomicInteger(0); - for (int i = 0; i < THREADS * THREADS; i++) { - delayQueues[i] = new ArrayList(); - } +// for (int i = 0; i < THREADS * THREADS; i++) { +// delayQueues[i] = new ArrayList(); +// } for (int i = 0; i < THREADS; i++) { // tasks[i] = new ArrayList(); - ownTasks[i] = new ArrayList(); - ownSyncTasks[i] = new ArrayList(); - queues[i] = new ArrayList(); - threadLocks[i] = new ReentrantLock(); - threadConditions[i] = threadLocks[i].newCondition(); +// ownTasks[i] = new ArrayList(); +// ownSyncTasks[i] = new ArrayList(); +// queues[i] = new ArrayList(); +// threadLocks[i] = new ReentrantLock(); +// threadConditions[i] = threadLocks[i].newCondition(); // limits[i] = false; threadStates[i] = ThreadState.INIT; @@ -365,31 +405,6 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } - directPredicatesMap = new UnaryQueryHashMap(); - valueMap = new UnaryQueryHashMap(); - principalTypesMap = new UnaryQueryHashMap(); - uriToResourceMap = new THashMap(); - namespaceIndexMap22 = new THashMap(); - projectsMap = new UnaryQueryHashMap(); - relationInfoMap = new UnaryQueryHashMap(); - typeHierarchyMap = new UnaryQueryHashMap(); - superTypesMap = new UnaryQueryHashMap(); - superRelationsMap = new UnaryQueryHashMap(); - typesMap = new UnaryQueryHashMap(); - objectsMap = new DoubleKeyQueryHashMap(); - orderedSetMap = new UnaryQueryHashMap(); - predicatesMap = new UnaryQueryHashMap(); - statementsMap = new DoubleKeyQueryHashMap(); - directObjectsMap = new DoubleKeyQueryHashMap(); - assertedPredicatesMap = new UnaryQueryHashMap(); - assertedStatementsMap = new BinaryQueryHashMap(); - asyncReadMap = new StableHashMap(); - readMap = new StableHashMap(); - asyncMultiReadMap = new StableHashMap(); - multiReadMap = new StableHashMap(); - externalReadMap = new StableHashMap(); - listeners = new THashMap>(10, 0.75f); - // Now start threads for (int i = 0; i < THREADS; i++) { executors[i].start(); @@ -571,48 +586,63 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap public void forResource(ReadGraphImpl graph, final String id, CacheEntry parent, final InternalProcedure procedure) { - URIToResource.queryEach(graph, id, parent, null, new InternalProcedure() { + try { + + QueryCache.runnerURIToResource(graph, id, parent, null, new InternalProcedure() { - @Override - public void execute(ReadGraphImpl graph, Integer result) { + @Override + public void execute(ReadGraphImpl graph, Integer result) throws DatabaseException { - if (result != null && result != 0) { - procedure.execute(graph, result); - return; - } + if (result != null && result != 0) { + procedure.execute(graph, result); + return; + } - // Fall back to using the fixed builtins. - result = querySupport.getBuiltin(id); - if (result != 0) { - procedure.execute(graph, result); - return; - } + // Fall back to using the fixed builtins. +// result = querySupport.getBuiltin(id); +// if (result != 0) { +// procedure.execute(graph, result); +// return; +// } - try { - result = querySupport.getRandomAccessReference(id); - } catch (ResourceNotFoundException e) { - procedure.exception(graph, e); - return; - } +// try { +// result = querySupport.getRandomAccessReference(id); +// } catch (ResourceNotFoundException e) { +// procedure.exception(graph, e); +// return; +// } - if (result != 0) { - procedure.execute(graph, result); - } else { - procedure.exception(graph, new ResourceNotFoundException(id)); - } + if (result != 0) { + procedure.execute(graph, result); + } else { + procedure.exception(graph, new ResourceNotFoundException(id)); + } - } + } - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - procedure.exception(graph, t); - } + @Override + public void exception(ReadGraphImpl graph, Throwable t) throws DatabaseException { + procedure.exception(graph, t); + } - }); + }); + } catch (DatabaseException e) { + + try { + + procedure.exception(graph, e); + + } catch (DatabaseException e1) { + + Logger.defaultLogError(e1); + + } + + } } - public void forBuiltin(ReadGraphImpl graph, final String id, CacheEntry parent, final InternalProcedure procedure) { + public void forBuiltin(ReadGraphImpl graph, final String id, CacheEntry parent, final InternalProcedure procedure) throws DatabaseException { Integer result = querySupport.getBuiltin(id); if (result != 0) { @@ -623,975 +653,155 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } - public final void runAsyncRead(final ReadGraphImpl graph, final AsyncRead query, final CacheEntry parent, final ListenerBase listener, final AsyncProcedure procedure) { - - int hash = requestHash(query); + final void runMultiRead(final ReadGraphImpl graph, MultiReadEntry cached, final MultiRead query, final CacheEntry parent, final QueryProcessor provider, final ListenerBase listener, final SyncMultiProcedure procedure) { - AsyncReadEntry entry = asyncReadMap.get(query, hash); - - if(parent == null && listener == null) { - if(entry != null && (entry.isReady() || entry.isExcepted())) { - System.out.println("ready " + query); - entry.performFromCache(graph, this, procedure); -// graph.state.barrier.dec(query); - return; - } else { - query.perform(graph, procedure); -// graph.state.barrier.dec(query); - return; - } + try { + QueryCache.runnerMultiReadEntry(graph, query, parent, listener, procedure); + } catch (DatabaseException e) { + throw new IllegalStateException(e); } - if(entry == null) { - - entry = new AsyncReadEntry(query); - entry.setPending(); - entry.clearResult(querySupport); - asyncReadMap.put(query, entry, hash); - - performForEach(graph, query, entry, parent, listener, procedure, false); - - } else { - - if(entry.isPending()) { - synchronized(entry) { - if(entry.isPending()) { - throw new IllegalStateException(); - // final AsyncBarrierImpl parentBarrier = graph.state.barrier; - // if(entry.procs == null) entry.procs = new ArrayList>(); - // entry.procs.add(new AsyncProcedure() { - // - // @Override - // public void execute(AsyncReadGraph graph, T result) { - // procedure.execute(graph, result); - // parentBarrier.dec(query); - // } - // - // @Override - // public void exception(AsyncReadGraph graph, Throwable throwable) { - // procedure.exception(graph, throwable); - // parentBarrier.dec(query); - // } - // - // }); -// if(graph.parent != null || listener != null) { -// registerDependencies(graph, entry, parent, listener, procedure, false); -// } -// -// query.perform(graph, procedure); -// -// return; - - } - } - } + } - if(entry.isReady()) { - entry.performFromCache(graph, this, procedure); - registerDependencies(graph, entry, parent, listener, procedure, false); - } else { - performForEach(graph, query, entry, parent, listener, procedure, false); - } + public final void runAsyncMultiRead(final ReadGraphImpl graph, final AsyncMultiRead query, final CacheEntry parent, final ListenerBase listener, final AsyncMultiProcedure procedure) { + + try { + QueryCache.runnerAsyncMultiReadEntry(graph, query, parent, listener, procedure); + } catch (DatabaseException e) { + throw new IllegalStateException(e); } } + final void runPrimitiveRead(ReadGraphImpl graph, ExternalReadEntry cached, final ExternalRead query, final CacheEntry parent, final QueryProcessor provider, final ListenerBase listener, final AsyncProcedure procedure) throws DatabaseException { + QueryCache.runnerExternalReadEntry(graph, query, parent, listener, procedure); + } - final static void runMultiRead(final ReadGraphImpl graph, MultiReadEntry cached, final MultiRead query, final CacheEntry parent, final QueryProcessor provider, final ListenerBase listener, final AsyncMultiProcedure procedure) { - - MultiReadEntry entry = cached != null ? cached : provider.multiReadMap.get(query); - if(entry == null) { - - entry = new MultiReadEntry(query); - entry.setPending(); - entry.clearResult(provider.querySupport); - - provider.multiReadMap.put(query, entry); - - provider.performForEach(graph, query, entry, parent, listener, procedure, false); - - } else { - - if(entry.isPending()) { - - synchronized(entry) { - - if(entry.isPending()) { - throw new IllegalStateException(); - -// if(entry.procs == null) entry.procs = new ArrayList, AsyncBarrier>>(); -// entry.procs.add(new Pair(procedure, parentBarrier)); -// if(graph.parent != null || listener != null) { -// provider.registerDependencies(graph, entry, parent, listener, procedure, false); -// } - - // If this was synchronized we must wait here until completion - // if(graph.state.synchronizedExecution) { - // while(entry.isPending()) { - // graph.resumeTasks(graph.callerThread, null, null); - // } - // } +// @Override +// public T query(final ReadGraphImpl graph, final Read query, final CacheEntry parent, final AsyncProcedure procedure, final ListenerBase listener) throws DatabaseException { +// +// return QueryCache.resultReadEntry(graph, query, parent, listener, procedure); // -// return; - - } - } +// } - entry.performFromCache(graph, provider, procedure); -// graph.state.barrier.dec(query); - return; + public void queryMultiRead(final ReadGraphImpl graph, final MultiRead query, final CacheEntry parent, final ListenerBase listener, final SyncMultiProcedure procedure) throws DatabaseException { - } else { + QueryCache.runnerMultiReadEntry(graph, query, parent, listener, procedure); - provider.performForEach(graph, query, entry, parent, listener, procedure, false); + } - } + public void queryPrimitiveRead(final ReadGraphImpl graph, final ExternalRead query, final CacheEntry parent, final ListenerBase listener, final AsyncProcedure procedure) throws DatabaseException { - } + QueryCache.runnerExternalReadEntry(graph, query, parent, listener, procedure); } - public final void runAsyncMultiRead(final ReadGraphImpl graph, final AsyncMultiRead query, final CacheEntry parent, final ListenerBase listener, final AsyncMultiProcedure procedure) { - - int hash = requestHash(query); + boolean isBound(ExternalReadEntry entry) { + if(entry.hasParents()) return true; + else if(hasListener(entry)) return true; + else return false; + } - AsyncMultiReadEntry entry = asyncMultiReadMap.get(query, hash); + synchronized public ListenerEntry registerDependencies(ReadGraphImpl graph, CacheEntry child, CacheEntry parent, ListenerBase listener, Object procedure, boolean inferred) { - if(parent == null && listener == null) { - if(entry != null && (entry.isReady() || entry.isExcepted())) { - System.out.println("ready " + query); - entry.performFromCache(graph, this, procedure); - return; - } else { - query.perform(graph, procedure); - return; + if (parent != null && !inferred) { + try { + if(!child.isImmutable(graph)) + child.addParent(parent); + } catch (DatabaseException e) { + Logger.defaultLogError(e); } - } - - if(entry == null) { - - entry = new AsyncMultiReadEntry(query); - entry.setPending(); - entry.clearResult(querySupport); - - asyncMultiReadMap.put(query, entry, hash); - - performForEach(graph, query, entry, parent, listener, procedure, false); - - } else { - - if(entry.isPending()) { - - synchronized(entry) { - if(entry.isPending()) { - throw new IllegalStateException(); -// if(entry.procs == null) entry.procs = new ArrayList>(); -// entry.procs.add(procedure); -// if(graph.parent != null || listener != null) { -// registerDependencies(graph, entry, parent, listener, procedure, false); -// } -// return; - } + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_DEPENDENCIES, Bindings.BOOLEAN)) { + System.out.println(child + " -> " + parent); } } - - performForEach(graph, query, entry, parent, listener, procedure, false); - } - } - - final static void runPrimitiveRead(ReadGraphImpl graph, ExternalReadEntry cached, final ExternalRead query, final CacheEntry parent, final QueryProcessor provider, final ListenerBase listener, final Procedure procedure) { - - final ExternalReadEntry entry = cached != null ? cached : provider.externalReadMap.get(query); - if(entry == null) { - provider.performForEach(graph, query, new ExternalReadEntry(query), parent, listener, procedure, false); + if (listener != null) { + return registerListener(child, listener, procedure); } else { - if(entry.isPending()) { - synchronized(entry) { - if(entry.isPending()) { - throw new IllegalStateException(); -// if(entry.procs == null) entry.procs = new ArrayList>(); -// entry.procs.add(procedure); -// return; - } - } - } - provider.performForEach(graph, query, entry, parent, listener, procedure, false); + return null; } } - public int requestHash(Object object) { - try { - return object.hashCode(); - } catch (Throwable t) { - Logger.defaultLogError(t); - return 0; - } - } - @Override - public T queryRead(final ReadGraphImpl graph, final Read query, final CacheEntry parent, final AsyncProcedure procedure, final ListenerBase listener) throws Throwable { - - assert(query != null); - - ReadEntry entry = readMap.get(query); + static class Dummy implements InternalProcedure, IntProcedure { - if(entry != null) { - if(parent == null && (listener == null || listener.isDisposed()) && entry.isReady()) { - return (T)entry.get(graph, this, procedure); - } else if (entry.isPending()) { - throw new IllegalStateException(); - } + @Override + public void execute(ReadGraphImpl graph, int i) { } - if(entry == null) { - - entry = new ReadEntry(query); - entry.setPending(); - entry.clearResult(querySupport); - - readMap.put(query, entry); - - return (T)performForEach(graph, query, entry, parent, listener, procedure, false); - - } else { - - if(entry.isPending()) { - throw new IllegalStateException(); - } else { - return (T)performForEach(graph, query, entry, parent, listener, procedure, false); - } - + @Override + public void finished(ReadGraphImpl graph) { } - } - - public void queryMultiRead(final ReadGraphImpl graph, final MultiRead query, final CacheEntry parent, final ListenerBase listener, final AsyncMultiProcedure procedure) { - - assert(query != null); - assert(procedure != null); - - final MultiReadEntry entry = multiReadMap.get(query); - - if(parent == null && !(listener != null)) { - if(entry != null && entry.isReady()) { - entry.performFromCache(graph, this, procedure); - return; - } + @Override + public void execute(ReadGraphImpl graph, Object result) { } - runMultiRead(graph, entry, query, parent, this, listener, procedure); - + @Override + public void exception(ReadGraphImpl graph, Throwable throwable) { + } + } + + private static final Dummy dummy = new Dummy(); - public void queryPrimitiveRead(final ReadGraphImpl graph, final ExternalRead query, final CacheEntry parent, final ListenerBase listener, final Procedure procedure) { + /* + public Object performForEach2(ReadGraphImpl graph, UnaryQuery query, CacheEntry parent, ListenerBase listener, Procedure procedure) throws Throwable { - assert(query != null); - assert(procedure != null); + if (DebugPolicy.PERFORM) + System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); - final ExternalReadEntry entry = externalReadMap.get(query); + assert (!dirty); + assert (!collecting); - if(parent == null && !(listener != null)) { - if(entry != null && entry.isReady()) { - entry.performFromCache(procedure); - return; - } - } + assert(query.assertNotDiscarded()); - runPrimitiveRead(graph, entry, query, parent, this, listener, procedure); + registerDependencies(graph, query, parent, listener, procedure, false); - } + // FRESH, REFUTED, EXCEPTED go here + if (!query.isReady()) { - public void performForEach(ReadGraphImpl parentGraph, final AsyncRead query, final AsyncReadEntry entry, final CacheEntry parent, final ListenerBase base, final AsyncProcedure procedure, - boolean inferredDependency) { + size++; + misses++; - if (DebugPolicy.PERFORM) - System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); + query.computeForEach(graph, this, (Procedure)dummy, true); + return query.get(graph, this, null); - assert (!dirty); - assert (!collecting); + } else { - assert(!entry.isDiscarded()); + hits++; - final ListenerEntry listenerEntry = registerDependencies(parentGraph, entry, parent, base, procedure, inferredDependency); + return query.get(graph, this, procedure); - // FRESH, REFUTED, EXCEPTED go here - if (!entry.isReady()) { + } - entry.setPending(); + } + */ + - size++; + interface QueryCollectorSupport { + public CacheCollectionResult allCaches(); + public Collection getRootList(); + public int getCurrentSize(); + public int calculateCurrentSize(); + public CacheEntryBase iterate(int level); + public void remove(); + public void setLevel(CacheEntryBase entry, int level); + public boolean start(boolean flush); + } - try { + interface QueryCollector { - final ReadGraphImpl finalParentGraph = parentGraph; + public void collect(int youngTarget, int allowedTimeInMs); - query.perform(parentGraph.withParent(entry), new AsyncProcedure() { + } - @Override - public void execute(AsyncReadGraph returnGraph, T result) { - ReadGraphImpl impl = (ReadGraphImpl)returnGraph; - //AsyncReadGraph resumeGraph = finalParentGraph.newAsync(); - entry.addOrSet(finalParentGraph, result); - if(listenerEntry != null) { - primeListenerEntry(listenerEntry, result); - } - try { - procedure.execute(finalParentGraph, result); - } catch (Throwable t) { - t.printStackTrace(); - } -// parentBarrier.dec(query); - } - - @Override - public void exception(AsyncReadGraph returnGraph, Throwable t) { - ReadGraphImpl impl = (ReadGraphImpl)returnGraph; -// AsyncReadGraph resumeGraph = finalParentGraph.newAsync(); - entry.except(finalParentGraph, t); - try { - procedure.exception(finalParentGraph, t); - } catch (Throwable t2) { - t2.printStackTrace(); - } -// parentBarrier.dec(query); - } - - @Override - public String toString() { - return procedure.toString(); - } - - }); - - } catch (Throwable t) { - - entry.except(t); - try { - procedure.exception(parentGraph, t); - } catch (Throwable t2) { - t2.printStackTrace(); - } -// parentBarrier.dec(query); - - } - - misses++; - - } else { - - entry.performFromCache(parentGraph, this, new AsyncProcedure() { - - @Override - public void exception(AsyncReadGraph graph, Throwable throwable) { - procedure.exception(graph, throwable); - } - - @Override - public void execute(AsyncReadGraph graph, T result) { - procedure.execute(graph, result); - if(listenerEntry != null) { - primeListenerEntry(listenerEntry, result); - } - } - - }); - -// parentBarrier.dec(query); - - hits++; - - } - - assert (!entry.isDiscarded()); - - } - - public T performForEach(final ReadGraphImpl graph, final Read query, final ReadEntry entry, final CacheEntry parent, final ListenerBase listener, final AsyncProcedure procedure, - boolean inferredDependency) throws Throwable { - - if (DebugPolicy.PERFORM) - System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); - - assert (!dirty); - assert (!collecting); - - entry.assertNotDiscarded(); - - if(entry.isReady()) { - - // EXCEPTED goes here - -// if(procedure != null) entry.performFromCache(graph, this, procedure); -// parentBarrier.dec(query); - hits++; - - ListenerEntry listenerEntry = registerDependencies(graph, entry, parent, listener, procedure, inferredDependency); - - T result = (T)entry.get(graph, this, procedure); - - if(listenerEntry != null) primeListenerEntry(listenerEntry, result); - - return result; - - } else { - - // FRESH, REFUTED, PENDING go here - - entry.setPending(); - - size++; - misses++; - - ListenerEntry listenerEntry = registerDependencies(graph, entry, parent, listener, procedure, inferredDependency); - - final ReadGraphImpl performGraph = graph.newSync(entry); - - try { - - if(Development.DEVELOPMENT) - Development.recordHistogram("run " + query); - - T result = query.perform(performGraph); - entry.addOrSet(performGraph, result); - - if(listenerEntry != null) primeListenerEntry(listenerEntry, result); - - return (T)entry.get(graph, this, procedure); - - } catch (Throwable t) { - - entry.except(t); - return (T)entry.get(graph, this, procedure); - - } - - } - - } - - public void performForEach(final ReadGraphImpl graph, final MultiRead query, final MultiReadEntry entry, CacheEntry parent, final ListenerBase listener, final AsyncMultiProcedure procedure, - boolean inferredDependency) { - - if (DebugPolicy.PERFORM) - System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); - - assert (!dirty); - assert (!collecting); - - assert(!entry.isPending()); - assert(!entry.isDiscarded()); - - // FRESH, REFUTED, EXCEPTED go here - if (!entry.isReady()) { - - entry.setPending(); - entry.clearResult(querySupport); - - multiReadMap.put(query, entry); - size++; - - final ReadGraphImpl newGraph = graph.newSync(entry); -// newGraph.state.barrier.inc(); - - try { - - query.perform(newGraph, new AsyncMultiProcedure() { - - @Override - public void execute(AsyncReadGraph graph, T result) { - entry.addOrSet(result); - try { - procedure.execute(graph, result); - } catch (Throwable t) { - t.printStackTrace(); - } - } - - @Override - public void finished(AsyncReadGraph graph) { - entry.finish(graph); - try { - procedure.finished(graph); - } catch (Throwable t) { - t.printStackTrace(); - } -// newGraph.state.barrier.dec(); -// parentBarrier.dec(); - } - - @Override - public void exception(AsyncReadGraph graph, Throwable t) { - entry.except(t); - try { - procedure.exception(graph, t); - } catch (Throwable t2) { - t2.printStackTrace(); - } -// newGraph.state.barrier.dec(); -// parentBarrier.dec(); - } - - }); - - } catch (DatabaseException e) { - - entry.except(e); - try { - procedure.exception(graph, e); - } catch (Throwable t2) { - t2.printStackTrace(); - } -// newGraph.state.barrier.dec(); -// parentBarrier.dec(); - - } catch (Throwable t) { - - DatabaseException e = new DatabaseException(t); - - entry.except(e); - try { - procedure.exception(graph, e); - } catch (Throwable t2) { - t2.printStackTrace(); - } -// newGraph.state.barrier.dec(); -// parentBarrier.dec(); - - } - - misses++; - - } else { - - entry.performFromCache(graph, this, procedure); - hits++; - - - } - - assert (!entry.isDiscarded()); - - registerDependencies(graph, entry, parent, listener, procedure, inferredDependency); - - } - - - public void performForEach(final ReadGraphImpl callerGraph, AsyncMultiRead query, final AsyncMultiReadEntry entry, final CacheEntry parent, final ListenerBase listener, final AsyncMultiProcedure procedure, - boolean inferredDependency) { - - if (DebugPolicy.PERFORM) - System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); - - assert (!dirty); - assert (!collecting); - - try { - - assert(!entry.isDiscarded()); - - // FRESH, REFUTED, EXCEPTED go here - if (!entry.isReady()) { - - size++; - - try { - - ReadGraphImpl performGraph = callerGraph.withAsyncParent(entry); - - query.perform(performGraph, new AsyncMultiProcedure() { - - @Override - public void execute(AsyncReadGraph graph, T result) { - ReadGraphImpl impl = (ReadGraphImpl)graph; -// ReadGraphImpl executeGraph = callerGraph.newAsync(); - entry.addOrSet(result); - try { - procedure.execute(callerGraph, result); - } catch (Throwable t) { - t.printStackTrace(); - } - } - - @Override - public void finished(AsyncReadGraph graph) { - ReadGraphImpl impl = (ReadGraphImpl)graph; -// ReadGraphImpl executeGraph = callerGraph.newAsync(); - entry.finish(callerGraph); - try { - procedure.finished(callerGraph); - } catch (Throwable t) { - t.printStackTrace(); - } - } - - @Override - public void exception(AsyncReadGraph graph, Throwable t) { - ReadGraphImpl impl = (ReadGraphImpl)graph; -// ReadGraphImpl executeGraph = callerGraph.newAsync(); - entry.except(callerGraph, t); - try { - procedure.exception(callerGraph, t); - } catch (Throwable t2) { - t2.printStackTrace(); - } - } - - }); - - } catch (Throwable t) { - - entry.except(t); - try { - procedure.exception(callerGraph, t); - } catch (Throwable t2) { - t2.printStackTrace(); - } - - } - - - misses++; - - } else { - - entry.performFromCache(callerGraph, this, procedure); - - hits++; - - } - - assert (!entry.isDiscarded()); - - registerDependencies(callerGraph, entry, parent, listener, procedure, inferredDependency); - - } catch (Throwable t) { - - Logger.defaultLogError(t); - - } finally { - - } - - } - - public void performForEach(ReadGraphImpl graph, final ExternalRead query, final ExternalReadEntry entry, final CacheEntry parent, final ListenerBase base, final Procedure procedure, - boolean inferredDependency) { - - if (DebugPolicy.PERFORM) - System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); - - assert (!dirty); - assert (!collecting); - - assert(!entry.isPending()); - assert(!entry.isDiscarded()); - - registerDependencies(graph, entry, parent, base, procedure, inferredDependency); - - // FRESH, REFUTED, EXCEPTED go here - if (!entry.isReady()) { - - entry.setPending(); - entry.clearResult(querySupport); - - externalReadMap.put(query, entry); - size++; - - try { - - query.register(graph, new Listener() { - - AtomicBoolean used = new AtomicBoolean(false); - - @Override - public void execute(T result) { - - // Just for safety - if(entry.isDiscarded()) return; - if(entry.isExcepted()) entry.setPending(); - - if(used.compareAndSet(false, true)) { - entry.addOrSet(QueryProcessor.this, result); - procedure.execute(result); - } else { - entry.queue(result); - updatePrimitive(query); - } - - } - - @Override - public void exception(Throwable t) { - - entry.except(t); - - if(used.compareAndSet(false, true)) { - procedure.exception(t); - } else { -// entry.queue(result); - updatePrimitive(query); - } - - } - - @Override - public String toString() { - return procedure.toString(); - } - - @Override - public boolean isDisposed() { - return entry.isDiscarded() || !isBound(entry); - } - - }); - - } catch (Throwable t) { - - entry.except(t); - procedure.exception(t); - - } - - misses++; - - } else { - - entry.performFromCache(procedure); - - hits++; - - } - - assert (!entry.isDiscarded()); - - } - - private boolean isBound(ExternalReadEntry entry) { - if(entry.hasParents()) return true; - else if(hasListener(entry)) return true; - else return false; - } - - synchronized public ListenerEntry registerDependencies(ReadGraphImpl graph, CacheEntry child, CacheEntry parent, ListenerBase listener, Object procedure, boolean inferred) { - - if (parent != null && !inferred) { - try { - if(!child.isImmutable(graph)) - child.addParent(parent); - } catch (DatabaseException e) { - Logger.defaultLogError(e); - } - if(DebugPolicy.DEPENDENCIES) System.out.println(child + " -> " + parent); - } - - if (listener != null) { - return registerListener(child, listener, procedure); - } else { - return null; - } - - } - - public void performForEach(ReadGraphImpl graph, BinaryQuery query, CacheEntry parent, ListenerBase listener, Procedure procedure) { - - if (DebugPolicy.PERFORM) - System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); - - assert (!dirty); - assert (!collecting); - - try { - - registerDependencies(graph, query, parent, listener, procedure, false); - - // FRESH, REFUTED, EXCEPTED go here - if (!query.isReady()) { - - boolean fresh = query.isFresh(); - - if(fresh) { - size++; - } - - query.computeForEach(graph, this, procedure, true); - - misses++; - - } else { - - query.performFromCache(graph, this, procedure); - - hits++; - - } - - } catch (Throwable t) { - - Logger.defaultLogError(t); - - } - } - - public Object performForEach(ReadGraphImpl graph, UnaryQuery query, CacheEntry parent, ListenerBase listener, Procedure procedure) { - - if (DebugPolicy.PERFORM) - System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); - - assert (!dirty); - assert (!collecting); - - try { - - assert(query.assertNotDiscarded()); - - registerDependencies(graph, query, parent, listener, procedure, false); - - // FRESH, REFUTED, EXCEPTED go here - if (!query.isReady()) { - - size++; - misses++; - - return query.computeForEach(graph, this, procedure, true); - - - } else { - - hits++; - - return query.performFromCache(graph, this, procedure); - - } - - } catch (Throwable t) { - - Logger.defaultLogError(t); - return null; - - } - - } - - static class Dummy implements InternalProcedure, IntProcedure { - - @Override - public void execute(ReadGraphImpl graph, int i) { - } - - @Override - public void finished(ReadGraphImpl graph) { - } - - @Override - public void execute(ReadGraphImpl graph, Object result) { - } - - @Override - public void exception(ReadGraphImpl graph, Throwable throwable) { - } - - } - - private static final Dummy dummy = new Dummy(); - - public Object performForEach2(ReadGraphImpl graph, UnaryQuery query, CacheEntry parent, ListenerBase listener, Procedure procedure) throws Throwable { - - if (DebugPolicy.PERFORM) - System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); - - assert (!dirty); - assert (!collecting); - - assert(query.assertNotDiscarded()); - - registerDependencies(graph, query, parent, listener, procedure, false); - - // FRESH, REFUTED, EXCEPTED go here - if (!query.isReady()) { - - size++; - misses++; - - query.computeForEach(graph, this, (Procedure)dummy, true); - return query.get(graph, this, null); - - } else { - - hits++; - - return query.get(graph, this, procedure); - - } - - } - - public void performForEach(ReadGraphImpl graph, StringQuery query, CacheEntry parent, final ListenerBase listener, Procedure procedure) { - - if (DebugPolicy.PERFORM) - System.out.println("PE[ " + (query.hashCode() & THREAD_MASK) + "] " + query); - - assert (!dirty); - assert (!collecting); - - try { - - if(query.isDiscarded()) { - System.err.println("aff"); - } - assert(!query.isDiscarded()); - - // FRESH, REFUTED, EXCEPTED go here - if (!query.isReady()) { - - query.computeForEach(graph.withAsyncParent(query), this, procedure); - - size++; - misses++; - - } else { - - query.performFromCache(graph, this, procedure); - - hits++; - - } - - assert (!query.isDiscarded()); - - registerDependencies(graph, query, parent, listener, procedure, false); - - } catch (Throwable t) { - - t.printStackTrace(); - Logger.defaultLogError(t); - - } - - } - - interface QueryCollectorSupport { - public CacheCollectionResult allCaches(); - public Collection getRootList(); - public int getCurrentSize(); - public int calculateCurrentSize(); - public CacheEntryBase iterate(int level); - public void remove(); - public void setLevel(CacheEntryBase entry, int level); - public boolean start(boolean flush); - } - - interface QueryCollector { - - public void collect(int youngTarget, int allowedTimeInMs); - - } - - class QueryCollectorSupportImpl implements QueryCollectorSupport { + class QueryCollectorSupportImpl implements QueryCollectorSupport { private static final boolean DEBUG = false; private static final double ITERATION_RATIO = 0.2; @@ -1690,106 +900,17 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } public Collection getRootList() { - - ArrayList result = new ArrayList(); - - for (Object e : valueMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : directPredicatesMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : objectsMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : directObjectsMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : principalTypesMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : superRelationsMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : superTypesMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : typesMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : objectsMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : assertedStatementsMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : readMap.values()) { - if(e instanceof CacheEntry) { - result.add((CacheEntry) e); - } else { - System.err.println("e=" + e); - } - } - for (Object e : asyncReadMap.values()) { - if(e instanceof CacheEntry) { - result.add((CacheEntry) e); - } else { - System.err.println("e=" + e); - } - } - for (Object e : externalReadMap.values()) { - result.add((CacheEntry) e); - } - for (Object e : orderedSetMap.values()) { - result.add((CacheEntry) e); - } - - return result; - + return cache.getRootList(); } @Override public int calculateCurrentSize() { - - int realSize = 0; - - realSize += directPredicatesMap.size(); - realSize += principalTypesMap.size(); - realSize += uriToResourceMap.size(); - realSize += namespaceIndexMap22.size(); - realSize += projectsMap.size(); - - realSize += relationInfoMap.size(); - realSize += superTypesMap.size(); - realSize += typeHierarchyMap.size(); - realSize += superRelationsMap.size(); - realSize += typesMap.size(); - - realSize += valueMap.size(); - realSize += directObjectsMap.size(); - realSize += objectsMap.size(); - realSize += orderedSetMap.size(); - realSize += predicatesMap.size(); - - realSize += statementsMap.size(); - realSize += assertedPredicatesMap.size(); - realSize += assertedStatementsMap.size(); - realSize += externalReadMap.size(); - realSize += asyncReadMap.size(); - - realSize += readMap.size(); - realSize += asyncMultiReadMap.size(); - realSize += multiReadMap.size(); - - size = realSize; - - return realSize; - + return cache.calculateCurrentSize(); } @Override public int getCurrentSize() { - return size; + return cache.size; } } @@ -1799,7 +920,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap private QueryCollector collector = new QueryCollectorImpl(this, collectorSupport); public int querySize() { - return size; + return cache.size; } public void gc(int youngTarget, int allowedTimeInMs) { @@ -1828,10 +949,10 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap assert (entry != null); assert (procedure != null); - ArrayList list = listeners.get(entry); + ArrayList list = cache.listeners.get(entry); if (list == null) { list = new ArrayList(1); - listeners.put(entry, list); + cache.listeners.put(entry, list); } ListenerEntry result = new ListenerEntry(entry, base, procedure); @@ -1845,9 +966,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap list.add(result); } - if(DebugPolicy.LISTENER) { - new Exception().printStackTrace(); - System.out.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + new Exception().printStackTrace(); + System.err.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure); + } } return result; @@ -1856,28 +979,32 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap private void scheduleListener(ListenerEntry entry) { assert (entry != null); - if(DebugPolicy.LISTENER) System.out.println("Scheduled " + entry.procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + System.err.println("Scheduled " + entry.procedure); + } + } scheduledListeners.add(entry); } private void removeListener(ListenerEntry entry) { assert (entry != null); - ArrayList list = listeners.get(entry.entry); + ArrayList list = cache.listeners.get(entry.entry); if(list == null) return; boolean success = list.remove(entry); assert (success); if (list.isEmpty()) - listeners.remove(entry.entry); + cache.listeners.remove(entry.entry); } private boolean hasListener(CacheEntry entry) { - if(listeners.get(entry) != null) return true; + if(cache.listeners.get(entry) != null) return true; return false; } boolean hasListenerAfterDisposing(CacheEntry entry) { - if(listeners.get(entry) != null) { - ArrayList entries = listeners.get(entry); + if(cache.listeners.get(entry) != null) { + ArrayList entries = cache.listeners.get(entry); ArrayList list = null; for (ListenerEntry e : entries) { if (e.base.isDisposed()) { @@ -1891,7 +1018,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } } if (entries.isEmpty()) { - listeners.remove(entry); + cache.listeners.remove(entry); return false; } return true; @@ -1901,13 +1028,13 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap List getListenerEntries(CacheEntry entry) { hasListenerAfterDisposing(entry); - if(listeners.get(entry) != null) - return listeners.get(entry); + if(cache.listeners.get(entry) != null) + return cache.listeners.get(entry); else return Collections.emptyList(); } - void processListenerReport(CacheEntry entry, Map> workarea) { + void processListenerReport(CacheEntry entry, Map> workarea) { if(!workarea.containsKey(entry)) { @@ -2078,7 +1205,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap int unboundCounter = 0; int unknownCounter = 0; - for(CacheEntry entry : workarea.keySet()) { + for(CacheEntry entry : workarea.keySet()) { //System.err.println("process " + entry); @@ -2286,8 +1413,8 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap query.removeEntry(this); - updates++; - size--; + cache.updates++; + cache.size--; if((entry.getGCStatus() & CacheEntry.HAS_BEEN_BOUND) != 0) boundQueries--; @@ -2308,8 +1435,6 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap CacheEntry entry = e.entry; -// System.err.println("updateQuery " + entry); - /* * If the dependency graph forms a DAG, some entries are inserted in the * todo list many times. They only need to be processed once though. @@ -2317,32 +1442,32 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap if (entry.isDiscarded()) { if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("D"); + System.err.print("D"); for (int i = 0; i < e.indent; i++) - System.out.print(" "); - System.out.println(entry.getQuery()); + System.err.print(" "); + System.err.println(entry.getQuery()); } } // System.err.println(" => DISCARDED"); return false; } - if (entry.isRefuted()) { - if (Development.DEVELOPMENT) { - if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("R"); - for (int i = 0; i < e.indent; i++) - System.out.print(" "); - System.out.println(entry.getQuery()); - } - } - return false; - } +// if (entry.isRefuted()) { +// if (Development.DEVELOPMENT) { +// if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { +// System.err.print("R"); +// for (int i = 0; i < e.indent; i++) +// System.err.print(" "); +// System.err.println(entry.getQuery()); +// } +// } +// return false; +// } if (entry.isExcepted()) { if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("E"); + System.err.print("E"); } } } @@ -2350,19 +1475,19 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap if (entry.isPending()) { if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("P"); + System.err.print("P"); } } } - updates++; + cache.updates++; if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("U "); + System.err.print("U "); for (int i = 0; i < e.indent; i++) - System.out.print(" "); - System.out.print(entry.getQuery()); + System.err.print(" "); + System.err.print(entry.getQuery()); } } @@ -2374,9 +1499,9 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { if(hasListener(entry)) { - System.out.println(" (L)"); + System.err.println(" (L)"); } else { - System.out.println(""); + System.err.println(""); } } } @@ -2420,7 +1545,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // System.err.println(" => FOO " + type); if (hasListener) { - ArrayList entries = listeners.get(entry); + ArrayList entries = cache.listeners.get(entry); if(entries != null) { for (ListenerEntry le : entries) { scheduleListener(le); @@ -2498,23 +1623,29 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap Query query = entry.getQuery(); - if(DebugPolicy.RECOMPUTE) System.out.println("R " + query); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_RECOMPUTE, Bindings.BOOLEAN)) { + System.err.println("R " + query); + } + } entry.prepareRecompute(querySupport); - ReadGraphImpl parentGraph = graph.withParent(entry); + ReadGraphImpl parentGraph = graph.forRecompute(entry); - query.recompute(parentGraph, this, entry); + query.recompute(parentGraph); if(entry.isExcepted()) return ListenerEntry.NO_VALUE; Object newValue = entry.getResult(); if (ListenerEntry.NO_VALUE == oldValue) { - if(DebugPolicy.CHANGES) { - System.out.println("C " + query); - System.out.println("- " + oldValue); - System.out.println("- " + newValue); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_CHANGES, Bindings.BOOLEAN)) { + System.out.println("C " + query); + System.out.println("- " + oldValue); + System.out.println("- " + newValue); + } } return newValue; } @@ -2530,10 +1661,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } else changed = (oldValue != null); - if(DebugPolicy.CHANGES && changed) { - System.out.println("C " + query); - System.out.println("- " + oldValue); - System.out.println("- " + newValue); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_CHANGES, Bindings.BOOLEAN)) { + System.err.println("C " + query); + System.err.println("- " + oldValue); + System.err.println("- " + newValue); + } } return changed ? newValue : ListenerEntry.NOT_CHANGED; @@ -2555,7 +1688,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap public void performScheduledUpdates(WriteGraphImpl graph) { assert (!updating); - assert (!collecting); + assert (!cache.collecting); assert (!firingListeners); firingListeners = true; @@ -2578,7 +1711,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap for (ListenerEntry listenerEntry : entries) { if (pruneListener(listenerEntry)) { - if(DebugPolicy.LISTENER) System.out.println("Pruned " + listenerEntry.procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + new Exception().printStackTrace(); + System.err.println("Pruned " + listenerEntry.procedure); + } + } continue; } @@ -2588,8 +1726,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap Object newValue = compareTo(graph, entry, listenerEntry.getLastKnown()); if (newValue != ListenerEntry.NOT_CHANGED) { - if(DebugPolicy.LISTENER) - System.out.println("Add to schedule " + listenerEntry.procedure + " with " + newValue); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + new Exception().printStackTrace(); + System.err.println("Add to schedule " + listenerEntry.procedure + " with " + newValue); + } + } schedule.add(listenerEntry); listenerEntry.setLastKnown(entry.getResult()); } @@ -2598,12 +1740,18 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap for(ListenerEntry listenerEntry : schedule) { final CacheEntry entry = listenerEntry.entry; - if(DebugPolicy.LISTENER) - System.out.println("Firing " + listenerEntry.procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + System.err.println("Firing " + listenerEntry.procedure); + } + } try { - if(DebugPolicy.LISTENER) - System.out.println("Firing " + listenerEntry.procedure + " for " + listenerEntry.entry); - entry.performFromCache(graph, this, listenerEntry.procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + System.err.println("Firing " + listenerEntry.procedure + " for " + listenerEntry.entry); + } + } + entry.performFromCache(graph, listenerEntry.procedure); } catch (Throwable t) { t.printStackTrace(); } @@ -2627,7 +1775,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap */ public boolean update(final ReadGraphImpl graph, final CacheEntry entry) { - assert (!collecting); + assert (!cache.collecting); assert (!updating); updating = true; @@ -2674,6 +1822,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } else { // If not changed, keep the old value immediate.setResult(oldValue); + immediate.setReady(); listenersUnknown = true; } @@ -2695,8 +1844,6 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } - volatile public boolean dirty = false; - private ObjectUpdateSet scheduledObjectUpdates = new ObjectUpdateSet(); private ValueUpdateSet scheduledValueUpdates = new ValueUpdateSet(); private ValueUpdateSet scheduledInvalidates = new ValueUpdateSet(); @@ -2704,9 +1851,25 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap private Object primitiveUpdateLock = new Object(); private THashSet scheduledPrimitiveUpdates = new THashSet(); + private ArrayList refutations = new ArrayList<>(); + + private void markForUpdate(ReadGraphImpl graph, CacheEntry e) { + e.refute(); + refutations.add(e); + } + + private void updateRefutations(ReadGraphImpl graph) { + + for(CacheEntry e : refutations) + update(graph, e); + + refutations.clear(); + + } + public void performDirtyUpdates(final ReadGraphImpl graph) { - dirty = false; + cache.dirty = false; lastInvalidate = 0; if (Development.DEVELOPMENT) { @@ -2723,28 +1886,37 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap final int subject = (int)(arg0 >>> 32); final int predicate = (int)(arg0 & 0xffffffff); - for(Objects o : Objects.entries(QueryProcessor.this, subject)) update(graph, o); - for(DirectObjects o : DirectObjects.entries(QueryProcessor.this, subject)) update(graph, o); - for(Statements o : Statements.entries(QueryProcessor.this, subject)) update(graph, o); + for(Objects o : QueryCache.entriesObjects(QueryProcessor.this, subject)) markForUpdate(graph, o); + for(DirectObjects o : QueryCache.entriesDirectObjects(QueryProcessor.this, subject)) markForUpdate(graph, o); + for(Statements o : QueryCache.entriesStatements(QueryProcessor.this, subject)) markForUpdate(graph, o); if(predicate == instanceOf || predicate == inherits || predicate == subrelationOf) { - PrincipalTypes principalTypes = PrincipalTypes.entry(QueryProcessor.this, subject); - if(principalTypes != null) update(graph, principalTypes); - Types types = Types.entry(QueryProcessor.this, subject); - if(types != null) update(graph, types); + PrincipalTypes principalTypes = QueryCache.entryPrincipalTypes(QueryProcessor.this, subject); + if(principalTypes != null) markForUpdate(graph, principalTypes); + Types types = QueryCache.entryTypes(QueryProcessor.this, subject); + if(types != null) markForUpdate(graph, types); } if(predicate == subrelationOf) { SuperRelations superRelations = SuperRelations.entry(QueryProcessor.this, subject); - if(superRelations != null) update(graph, superRelations); + if(superRelations != null) markForUpdate(graph, superRelations); } - DirectPredicates dp = DirectPredicates.entry(QueryProcessor.this, subject); - if(dp != null) update(graph, dp); - OrderedSet os = OrderedSet.entry(QueryProcessor.this, predicate); - if(os != null) update(graph, os); + DirectPredicates dp = QueryCache.entryDirectPredicates(QueryProcessor.this, subject); + if(dp != null) markForUpdate(graph, dp); + OrderedSet os = QueryCache.entryOrderedSet(QueryProcessor.this, predicate); + if(os != null) markForUpdate(graph, os); + updateRefutations(graph); + scheduledObjectUpdates.clear(); + + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { + System.err.println("== Query update ends =="); + } + } + return; } @@ -2754,10 +1926,19 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap int arg0 = scheduledValueUpdates.getFirst(); - ValueQuery valueQuery = ValueQuery.entry(QueryProcessor.this, arg0); - if(valueQuery != null) update(graph, valueQuery); + ValueQuery valueQuery = QueryCache.entryValueQuery(QueryProcessor.this, arg0); + if(valueQuery != null) markForUpdate(graph, valueQuery); + + updateRefutations(graph); scheduledValueUpdates.clear(); + + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { + System.err.println("== Query update ends =="); + } + } + return; } @@ -2771,30 +1952,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap scheduledPrimitiveUpdates = new THashSet(); } - primitiveUpdates.forEach(new TObjectProcedure() { - - @Override - public boolean execute(Object arg0) { - - ExternalReadEntry query = (ExternalReadEntry)externalReadMap.get(arg0); - if (query != null) { - boolean listening = update(graph, query); - if (!listening && !query.hasParents()) { - externalReadMap.remove(arg0); - query.discard(); - } - } - return true; - } - - }); - scheduledValueUpdates.forEach(new TIntProcedure() { @Override public boolean execute(int arg0) { - ValueQuery valueQuery = ValueQuery.entry(QueryProcessor.this, arg0); - if(valueQuery != null) update(graph, valueQuery); + ValueQuery valueQuery = QueryCache.entryValueQuery(QueryProcessor.this, arg0); + if(valueQuery != null) markForUpdate(graph, valueQuery); return true; } @@ -2805,16 +1968,16 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap @Override public boolean execute(int resource) { - ValueQuery valueQuery = ValueQuery.entry(QueryProcessor.this, resource); - if(valueQuery != null) update(graph, valueQuery); + ValueQuery valueQuery = QueryCache.entryValueQuery(QueryProcessor.this, resource); + if(valueQuery != null) markForUpdate(graph, valueQuery); - PrincipalTypes principalTypes = PrincipalTypes.entry(QueryProcessor.this, resource); - if(principalTypes != null) update(graph, principalTypes); - Types types = Types.entry(QueryProcessor.this, resource); - if(types != null) update(graph, types); + PrincipalTypes principalTypes = QueryCache.entryPrincipalTypes(QueryProcessor.this, resource); + if(principalTypes != null) markForUpdate(graph, principalTypes); + Types types = QueryCache.entryTypes(QueryProcessor.this, resource); + if(types != null) markForUpdate(graph, types); SuperRelations superRelations = SuperRelations.entry(QueryProcessor.this, resource); - if(superRelations != null) update(graph, superRelations); + if(superRelations != null) markForUpdate(graph, superRelations); predicates.add(resource); @@ -2832,15 +1995,15 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap final int predicate = (int)(arg0 & 0xffffffff); if(predicate == instanceOf || predicate == inherits || predicate == subrelationOf) { - PrincipalTypes principalTypes = PrincipalTypes.entry(QueryProcessor.this, subject); - if(principalTypes != null) update(graph, principalTypes); - Types types = Types.entry(QueryProcessor.this, subject); - if(types != null) update(graph, types); + PrincipalTypes principalTypes = QueryCache.entryPrincipalTypes(QueryProcessor.this, subject); + if(principalTypes != null) markForUpdate(graph, principalTypes); + Types types = QueryCache.entryTypes(QueryProcessor.this, subject); + if(types != null) markForUpdate(graph, types); } if(predicate == subrelationOf) { SuperRelations superRelations = SuperRelations.entry(QueryProcessor.this, subject); - if(superRelations != null) update(graph, superRelations); + if(superRelations != null) markForUpdate(graph, superRelations); } predicates.add(subject); @@ -2857,12 +2020,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap @Override public boolean execute(final int subject) { - for(Objects o : Objects.entries(QueryProcessor.this, subject)) update(graph, o); - for(DirectObjects o : DirectObjects.entries(QueryProcessor.this, subject)) update(graph, o); - for(Statements o : Statements.entries(QueryProcessor.this, subject)) update(graph, o); + for(Objects o : QueryCache.entriesObjects(QueryProcessor.this, subject)) markForUpdate(graph, o); + for(DirectObjects o : QueryCache.entriesDirectObjects(QueryProcessor.this, subject)) markForUpdate(graph, o); + for(Statements o : QueryCache.entriesStatements(QueryProcessor.this, subject)) markForUpdate(graph, o); - DirectPredicates entry = DirectPredicates.entry(QueryProcessor.this, subject); - if(entry != null) update(graph, entry); + DirectPredicates entry = QueryCache.entryDirectPredicates(QueryProcessor.this, subject); + if(entry != null) markForUpdate(graph, entry); return true; @@ -2875,8 +2038,8 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap @Override public boolean execute(int orderedSet) { - OrderedSet entry = OrderedSet.entry(QueryProcessor.this, orderedSet); - if(entry != null) update(graph, entry); + OrderedSet entry = QueryCache.entryOrderedSet(QueryProcessor.this, orderedSet); + if(entry != null) markForUpdate(graph, entry); return true; @@ -2884,32 +2047,46 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap }); - // for (Integer subject : predicates) { - // DirectPredicates entry = DirectPredicates.entry(QueryProcessor.this, subject); - // if(entry != null) update(graph, entry); - // } + updateRefutations(graph); + primitiveUpdates.forEach(new TObjectProcedure() { - if (Development.DEVELOPMENT) { - if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.err.println("== Query update ends =="); + @Override + public boolean execute(Object arg0) { + + ExternalReadEntry query = (ExternalReadEntry)cache.externalReadEntryMap.get(arg0); + if (query != null) { + boolean listening = update(graph, query); + if (!listening && !query.hasParents()) { + cache.externalReadEntryMap.remove(arg0); + query.discard(); + } + } + return true; } - } + }); + scheduledValueUpdates.clear(); scheduledObjectUpdates.clear(); scheduledInvalidates.clear(); + + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { + System.err.println("== Query update ends =="); + } + } } public void updateValue(final int resource) { scheduledValueUpdates.add(resource); - dirty = true; + cache.dirty = true; } public void updateStatements(final int resource, final int predicate) { scheduledObjectUpdates.add((((long)resource) << 32) + predicate); - dirty = true; + cache.dirty = true; } private int lastInvalidate = 0; @@ -2918,7 +2095,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap if(lastInvalidate == resource) return; scheduledValueUpdates.add(resource); lastInvalidate = resource; - dirty = true; + cache.dirty = true; } public void updatePrimitive(final ExternalRead primitive) { @@ -2934,7 +2111,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap @Override public synchronized String toString() { - return "QueryProvider [size = " + size + ", hits = " + hits + " misses = " + misses + ", updates = " + updates + "]"; + return "QueryProvider [size = " + cache.size + ", hits = " + cache.hits + " misses = " + cache.misses + ", updates = " + cache.updates + "]"; } @Override @@ -2990,28 +2167,28 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } public int getHits() { - return hits; + return cache.hits; } public int getMisses() { - return misses; + return cache.misses; } public int getSize() { - return size; + return cache.size; } public Set getReferencedClusters() { HashSet result = new HashSet(); - for (CacheEntry entry : objectsMap.values()) { + for (CacheEntry entry : QueryCache.entriesObjects(this)) { Objects query = (Objects) entry.getQuery(); result.add(querySupport.getClusterId(query.r1())); } - for (CacheEntry entry : directPredicatesMap.values()) { + for (CacheEntry entry : QueryCache.entriesDirectPredicates(this)) { DirectPredicates query = (DirectPredicates) entry.getQuery(); result.add(querySupport.getClusterId(query.id)); } - for (CacheEntry entry : valueMap.values()) { + for (CacheEntry entry : cache.valueQueryMap.values()) { ValueQuery query = (ValueQuery) entry.getQuery(); result.add(querySupport.getClusterId(query.id)); } @@ -3022,41 +2199,8 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } CacheCollectionResult allCaches(CacheCollectionResult result) { - - int level = Integer.MAX_VALUE; - directPredicatesMap.values(level, result); - principalTypesMap.values(level, result); - for(CacheEntryBase e : uriToResourceMap.values()) - if(e.getLevel() <= level) - result.add(e); - for(CacheEntryBase e : namespaceIndexMap22.values()) - if(e.getLevel() <= level) - result.add(e); - projectsMap.values(level, result); - relationInfoMap.values(level, result); - superTypesMap.values(level, result); - typeHierarchyMap.values(level, result); - superRelationsMap.values(level, result); - typesMap.values(level, result); - - valueMap.values(level, result); - directObjectsMap.values(level, result); - objectsMap.values(level, result); - orderedSetMap.values(level, result); - predicatesMap.values(level, result); - - statementsMap.values(level, result); - assertedPredicatesMap.values(level, result); - assertedStatementsMap.values(level, result); - externalReadMap.values(level, result); - asyncReadMap.values(level, result); - - readMap.values(level, result); - asyncMultiReadMap.values(level, result); - multiReadMap.values(level, result); - - return result; + return cache.allCaches(result); } @@ -3069,7 +2213,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap public int clean() { collector.collect(0, Integer.MAX_VALUE); - return size; + return cache.size; } public void clean(final Collection> requests) { @@ -3083,7 +2227,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap public CacheEntryBase iterate(int level) { if(iterator.hasNext()) { ExternalRead request = iterator.next(); - ExternalReadEntry entry = externalReadMap.get(request); + ExternalReadEntry entry = cache.externalReadEntryMap.get(request); if (entry != null) return entry; else return iterate(level); } else { @@ -3103,7 +2247,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap public Collection getRootList() { ArrayList result = new ArrayList(requests.size()); for (ExternalRead request : requests) { - ExternalReadEntry entry = externalReadMap.get(request); + ExternalReadEntry entry = cache.externalReadEntryMap.get(request); if (entry != null) result.add(entry); } @@ -3111,7 +2255,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } @Override public int getCurrentSize() { - return size; + return cache.size; } @Override public int calculateCurrentSize() { @@ -3127,48 +2271,8 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } public void scanPending() { - - ArrayList entries = new ArrayList(); - - entries.addAll(directPredicatesMap.values()); - entries.addAll(principalTypesMap.values()); - entries.addAll(uriToResourceMap.values()); - entries.addAll(namespaceIndexMap22.values()); - entries.addAll(projectsMap.values()); - entries.addAll(relationInfoMap.values()); - entries.addAll(superTypesMap.values()); - entries.addAll(superRelationsMap.values()); - entries.addAll(typesMap.values()); - entries.addAll(valueMap.values()); - entries.addAll(directObjectsMap.values()); - entries.addAll(objectsMap.values()); - entries.addAll(orderedSetMap.values()); - entries.addAll(predicatesMap.values()); - entries.addAll(orderedSetMap.values()); - entries.addAll(statementsMap.values()); - // entries.addAll(assertedObjectsMap.values()); - entries.addAll(assertedPredicatesMap.values()); - entries.addAll(assertedStatementsMap.values()); - entries.addAll(externalReadMap.values()); - entries.addAll(asyncReadMap.values()); - entries.addAll(externalReadMap.values()); - entries.addAll(readMap.values()); - entries.addAll(asyncMultiReadMap.values()); - entries.addAll(multiReadMap.values()); - entries.addAll(readMap.values()); - System.out.println(entries.size() + " entries."); - for(Object e : entries) { - if(e instanceof CacheEntry) { - CacheEntry en = (CacheEntry)e; - if(en.isPending()) System.out.println("pending " + e); - if(en.isExcepted()) System.out.println("excepted " + e); - if(en.isDiscarded()) System.out.println("discarded " + e); - if(en.isRefuted()) System.out.println("refuted " + e); - if(en.isFresh()) System.out.println("fresh " + e); - } else { - //System.out.println("Unknown object " + e); - } - } + + cache.scanPending(); } @@ -3215,159 +2319,109 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap builtinValues.put(b.StringArray, String[].class); builtinValues.put(b.DoubleArray, double[].class); - builtinValues.put(b.FloatArray, float[].class); - builtinValues.put(b.LongArray, long[].class); - builtinValues.put(b.IntegerArray, int[].class); - builtinValues.put(b.ByteArray, byte[].class); - builtinValues.put(b.BooleanArray, boolean[].class); - - } - -// public ReadGraphSupportImpl(final QueryProcessor provider2) { -// -// if (null == provider2) { -// this.processor = null; -// support = null; -// return; -// } -// this.processor = provider2; -// support = provider2.getCore(); -// initBuiltinValues(); -// -// } - -// final static public ReadGraphSupportImpl basedOn(ReadGraphSupportImpl impl) { -// return new ReadGraphSupportImpl(impl.processor); -// } - - @Override - final public Session getSession() { - return session; - } - - final public ResourceSupport getResourceSupport() { - return resourceSupport; - } - - @Override - final public void forEachPredicate(final ReadGraphImpl impl, final Resource subject, final AsyncMultiProcedure procedure) { - - assert(subject != null); - assert(procedure != null); - - final ListenerBase listener = getListenerBase(procedure); - - IntProcedure ip = new IntProcedure() { - - AtomicBoolean first = new AtomicBoolean(true); - - @Override - public void execute(ReadGraphImpl graph, int i) { - try { - if(first.get()) { - procedure.execute(graph, querySupport.getResource(i)); - } else { - procedure.execute(impl.newRestart(graph), querySupport.getResource(i)); - } - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } - } - - @Override - public void finished(ReadGraphImpl graph) { - try { - if(first.compareAndSet(true, false)) { - procedure.finished(graph); -// impl.state.barrier.dec(this); - } else { - procedure.finished(impl.newRestart(graph)); - } - - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } - } - - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - if(first.compareAndSet(true, false)) { - procedure.exception(graph, t); -// impl.state.barrier.dec(this); - } else { - procedure.exception(impl.newRestart(graph), t); - } - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } - } - - }; + builtinValues.put(b.FloatArray, float[].class); + builtinValues.put(b.LongArray, long[].class); + builtinValues.put(b.IntegerArray, int[].class); + builtinValues.put(b.ByteArray, byte[].class); + builtinValues.put(b.BooleanArray, boolean[].class); - int sId = querySupport.getId(subject); + } -// if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(ip, "#Predicates#" + sId); -// else impl.state.barrier.inc(null, null); +// public ReadGraphSupportImpl(final QueryProcessor provider2) { +// +// if (null == provider2) { +// this.processor = null; +// support = null; +// return; +// } +// this.processor = provider2; +// support = provider2.getCore(); +// initBuiltinValues(); +// +// } - Predicates.queryEach(impl, sId, this, impl.parent, listener, ip); +// final static public ReadGraphSupportImpl basedOn(ReadGraphSupportImpl impl) { +// return new ReadGraphSupportImpl(impl.processor); +// } + @Override + final public Session getSession() { + return session; + } + + final public ResourceSupport getResourceSupport() { + return resourceSupport; } @Override - final public void forEachPredicate(final ReadGraphImpl impl, final Resource subject, final MultiProcedure procedure) { - - assert(subject != null); - assert(procedure != null); + final public void forEachPredicate(final ReadGraphImpl impl, final Resource subject, final AsyncMultiProcedure procedure) { - final ListenerBase listener = getListenerBase(procedure); + try { -// impl.state.barrier.inc(); + for(Resource predicate : getPredicates(impl, subject)) + procedure.execute(impl, predicate); - Predicates.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, new IntProcedure() { + procedure.finished(impl); - @Override - public void execute(ReadGraphImpl graph, int i) { - try { - procedure.execute(querySupport.getResource(i)); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } - } + } catch (Throwable e) { + procedure.exception(impl, e); + } - @Override - public void finished(ReadGraphImpl graph) { - try { - procedure.finished(); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } -// impl.state.barrier.dec(); - } + } - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - procedure.exception(t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } -// impl.state.barrier.dec(); - } + @Override + final public void forEachPredicate(final ReadGraphImpl impl, final Resource subject, final MultiProcedure procedure) { + + throw new UnsupportedOperationException(); - }); +// assert(subject != null); +// assert(procedure != null); +// +// final ListenerBase listener = getListenerBase(procedure); +// +// try { +// QueryCache.runnerPredicates(impl, querySupport.getId(subject), impl.parent, listener, new IntProcedure() { +// +// @Override +// public void execute(ReadGraphImpl graph, int i) { +// try { +// procedure.execute(querySupport.getResource(i)); +// } catch (Throwable t2) { +// Logger.defaultLogError(t2); +// } +// } +// +// @Override +// public void finished(ReadGraphImpl graph) { +// try { +// procedure.finished(); +// } catch (Throwable t2) { +// Logger.defaultLogError(t2); +// } +//// impl.state.barrier.dec(); +// } +// +// @Override +// public void exception(ReadGraphImpl graph, Throwable t) { +// try { +// procedure.exception(t); +// } catch (Throwable t2) { +// Logger.defaultLogError(t2); +// } +//// impl.state.barrier.dec(); +// } +// +// }); +// } catch (DatabaseException e) { +// Logger.defaultLogError(e); +// } } @Override final public IntSet getPredicates(final ReadGraphImpl impl, final Resource subject) throws Throwable { - - assert(subject != null); - - return Predicates.queryEach2(impl, querySupport.getId(subject), this, impl.parent); - + return QueryCacheBase.resultPredicates(impl, querySupport.getId(subject), impl.parent, null); } - @Override final public void forEachStatement(final ReadGraphImpl impl, final Resource subject, @@ -3381,38 +2435,42 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // impl.state.barrier.inc(); - Statements.queryEach(impl, querySupport.getId(subject), querySupport.getId(predicate), this, impl.parent, listener, new TripleIntProcedureAdapter() { + try { + Statements.queryEach(impl, querySupport.getId(subject), querySupport.getId(predicate), this, impl.parent, listener, new TripleIntProcedureAdapter() { - @Override - public void execute(ReadGraphImpl graph, int s, int p, int o) { - try { - procedure.execute(querySupport.getStatement(s, p, o)); - } catch (Throwable t2) { - Logger.defaultLogError(t2); + @Override + public void execute(ReadGraphImpl graph, int s, int p, int o) { + try { + procedure.execute(querySupport.getStatement(s, p, o)); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } } - } - @Override - public void finished(ReadGraphImpl graph) { - try { - procedure.finished(); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + @Override + public void finished(ReadGraphImpl graph) { + try { + procedure.finished(); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } - - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - procedure.exception(t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); } + + @Override + public void exception(ReadGraphImpl graph, Throwable t) { + try { + procedure.exception(t); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } + } - }); + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -3485,7 +2543,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(proc, "#Statements" + sId + "#" + pId); // else impl.state.barrier.inc(null, null); - Statements.queryEach(impl, sId, pId, this, impl.parent, listener, proc); + try { + Statements.queryEach(impl, sId, pId, this, impl.parent, listener, proc); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -3558,7 +2620,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(proc, "#Statements" + sId + "#" + pId); // else impl.state.barrier.inc(null, null); - Statements.queryEach(impl, sId, pId, this, impl.parent, listener, proc); + try { + Statements.queryEach(impl, sId, pId, this, impl.parent, listener, proc); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -3630,38 +2696,42 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // impl.state.barrier.inc(); - AssertedStatements.queryEach(impl, querySupport.getId(subject), querySupport.getId(predicate), this, impl.parent, listener, new TripleIntProcedureAdapter() { + try { + QueryCache.runnerAssertedStatements(impl, querySupport.getId(subject), querySupport.getId(predicate), impl.parent, listener, new TripleIntProcedureAdapter() { - @Override - public void execute(ReadGraphImpl graph, int s, int p, int o) { - try { - procedure.execute(graph, querySupport.getStatement(s, p, o)); - } catch (Throwable t2) { - Logger.defaultLogError(t2); + @Override + public void execute(ReadGraphImpl graph, int s, int p, int o) { + try { + procedure.execute(graph, querySupport.getStatement(s, p, o)); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } } - } - @Override - public void finished(ReadGraphImpl graph) { - try { - procedure.finished(graph); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + @Override + public void finished(ReadGraphImpl graph) { + try { + procedure.finished(graph); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } - - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - procedure.exception(graph, t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); } + + @Override + public void exception(ReadGraphImpl graph, Throwable t) { + try { + procedure.exception(graph, t); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } + } - }); + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -3681,111 +2751,101 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // impl.state.barrier.inc(); - Objects.runner(impl, querySupport.getId(subject), querySupport.getId(predicate), impl.parent, listener, new IntProcedure() { + try { + QueryCache.runnerObjects(impl, querySupport.getId(subject), querySupport.getId(predicate), impl.parent, listener, new IntProcedure() { - @Override - public void execute(ReadGraphImpl graph, int i) { - try { - procedure.execute(querySupport.getResource(i)); - } catch (Throwable t2) { - Logger.defaultLogError(t2); + @Override + public void execute(ReadGraphImpl graph, int i) { + try { + procedure.execute(querySupport.getResource(i)); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } } - } - @Override - public void finished(ReadGraphImpl graph) { - try { - procedure.finished(); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + @Override + public void finished(ReadGraphImpl graph) { + try { + procedure.finished(); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } - - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - System.out.println("forEachObject exception " + t); - try { - procedure.exception(t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); } + + @Override + public void exception(ReadGraphImpl graph, Throwable t) { + System.out.println("forEachObject exception " + t); + try { + procedure.exception(t); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } + } - }); + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } - -// @Override -// final public void forEachDirectObject(final ReadGraphImpl impl, final Resource subject, final Resource predicate, final AsyncMultiProcedure procedure) { -// -// assert(subject != null); -// assert(predicate != null); -// assert(procedure != null); -// -// final ListenerBase listener = getListenerBase(procedure); -// -// int sId = querySupport.getId(subject); -// int pId = querySupport.getId(predicate); -// -// MultiIntProcedure proc = new MultiIntProcedure(procedure, impl, support); -// -// if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(proc, "#DirectObjects" + sId + "#" + pId); -// else impl.state.barrier.inc(null, null); -// -// // final Exception caller = new Exception(); -// -// // final Pair exceptions = Pair.make(callerException, new Exception()); -// -// DirectObjects.queryEach(impl, sId, pId, processor, impl.parent, listener, proc); -// -// } - @Override - final public void forEachDirectPredicate(final ReadGraphImpl impl, final Resource subject, final AsyncMultiProcedure procedure) { + final public void forEachDirectPredicate(final ReadGraphImpl impl, final Resource subject, final AsyncProcedure> procedure) { assert(subject != null); assert(procedure != null); final ListenerBase listener = getListenerBase(procedure); - MultiIntProcedure proc = new MultiIntProcedure(procedure, impl, querySupport); - int sId = querySupport.getId(subject); -// if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(proc, "#DirectPredicates" + sId); -// else impl.state.barrier.inc(null, null); - - DirectPredicates.queryEach(impl, sId, this, impl.parent, listener, proc); - - } - - @Override - final public void forEachDirectStatement(final ReadGraphImpl impl, final Resource subject, final Procedure procedure) { - - assert(subject != null); - assert(procedure != null); + try { + QueryCache.runnerDirectPredicates(impl, sId, impl.parent, listener, new InternalProcedure() { - final ListenerBase listener = getListenerBase(procedure); + @Override + public void execute(ReadGraphImpl graph, IntSet result) throws DatabaseException { + procedure.execute(graph, result); + } - org.simantics.db.impl.query.DirectStatements.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, procedure); + @Override + public void exception(ReadGraphImpl graph, Throwable throwable) throws DatabaseException { + procedure.exception(graph, throwable); + } + + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } - @Override - final public void forEachDirectStatement(final ReadGraphImpl impl, final Resource subject, final AsyncProcedure procedure, boolean ignoreVirtual) { - - assert(subject != null); - assert(procedure != null); - - final ListenerBase listener = getListenerBase(procedure); + final public DirectStatements getDirectStatements(final ReadGraphImpl impl, final Resource subject, final boolean ignoreVirtual) { - org.simantics.db.impl.query.DirectStatements.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, procedure, ignoreVirtual); +// assert(subject != null); +// assert(procedure != null); +// +// final ListenerBase listener = getListenerBase(procedure); +// +// org.simantics.db.impl.query.DirectStatements.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, procedure); + + return querySupport.getStatements(impl, querySupport.getId(subject), this, ignoreVirtual); } +// @Override +// final public void forEachDirectStatement(final ReadGraphImpl impl, final Resource subject, final SyncProcedure procedure, boolean ignoreVirtual) { +// +// assert(subject != null); +// assert(procedure != null); +// +// final ListenerBase listener = getListenerBase(procedure); +// +// org.simantics.db.impl.query.DirectStatements.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, procedure, ignoreVirtual); +// +// } + private static final Resource INVALID_RESOURCE = new ResourceImpl(null, Integer.MIN_VALUE); @Override @@ -3824,16 +2884,59 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap final int sId = querySupport.getId(subject); final int pId = querySupport.getId(predicate); - Objects.runner(impl, sId, pId, impl.parent, listener, procedure); + try { + QueryCache.runnerObjects(impl, sId, pId, impl.parent, listener, procedure); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } - final public int getSingleObject(final ReadGraphImpl impl, final Resource subject, final Resource predicate) throws DatabaseException { + static class Runner2Procedure implements IntProcedure { + + public int single = 0; + public Throwable t = null; + + public void clear() { + single = 0; + t = null; + } + + @Override + public void execute(ReadGraphImpl graph, int i) { + if(single == 0) single = i; + else single = -1; + } + + @Override + public void finished(ReadGraphImpl graph) { + if(single == -1) single = 0; + } - final int sId = querySupport.getId(subject); - final int pId = querySupport.getId(predicate); + @Override + public void exception(ReadGraphImpl graph, Throwable throwable) { + single = 0; + this.t = throwable; + } + + public int get() throws DatabaseException { + if(t != null) { + if(t instanceof DatabaseException) throw (DatabaseException)t; + else throw new DatabaseException(t); + } + return single; + } + + } + + final public int getSingleObject(final ReadGraphImpl impl, final Resource subject, final Resource predicate) throws DatabaseException { + + final int sId = querySupport.getId(subject); + final int pId = querySupport.getId(predicate); - return Objects.runner2(impl, sId, pId, impl.parent); + Runner2Procedure proc = new Runner2Procedure(); + QueryCache.runnerObjects(impl, sId, pId, impl.parent, null, proc); + return proc.get(); } @@ -4245,40 +3348,42 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap final ListenerBase listener = getListenerBase(procedure); -// impl.state.barrier.inc(); - - AssertedStatements.queryEach(impl, querySupport.getId(subject), querySupport.getId(predicate), this, impl.parent, listener, new TripleIntProcedure() { + try { + QueryCache.runnerAssertedStatements(impl, querySupport.getId(subject), querySupport.getId(predicate), impl.parent, listener, new TripleIntProcedure() { - @Override - public void execute(ReadGraphImpl graph, int s, int p, int o) { - try { - procedure.execute(graph, querySupport.getResource(o)); - } catch (Throwable t2) { - Logger.defaultLogError(t2); + @Override + public void execute(ReadGraphImpl graph, int s, int p, int o) { + try { + procedure.execute(graph, querySupport.getResource(o)); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } } - } - @Override - public void finished(ReadGraphImpl graph) { - try { - procedure.finished(graph); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + @Override + public void finished(ReadGraphImpl graph) { + try { + procedure.finished(graph); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } - - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - procedure.exception(graph, t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); } + + @Override + public void exception(ReadGraphImpl graph, Throwable t) { + try { + procedure.exception(graph, t); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } + } - }); + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -4328,7 +3433,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(ip, "#PrincipalTypes#" + sId); // else impl.state.barrier.inc(null, null); - PrincipalTypes.queryEach(impl, sId, this, impl.parent, listener, ip); + try { + QueryCache.runnerPrincipalTypes(impl, sId, impl.parent, listener, ip); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -4342,39 +3451,42 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // impl.state.barrier.inc(); - PrincipalTypes.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, new IntProcedure() { + try { + QueryCache.runnerPrincipalTypes(impl, querySupport.getId(subject), impl.parent, listener, new IntProcedure() { - @Override - public void execute(ReadGraphImpl graph, int i) { - try { - procedure.execute(querySupport.getResource(i)); - } catch (Throwable t2) { - Logger.defaultLogError(t2); + @Override + public void execute(ReadGraphImpl graph, int i) { + try { + procedure.execute(querySupport.getResource(i)); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } } - } - @Override - public void finished(ReadGraphImpl graph) { - try { - procedure.finished(); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + @Override + public void finished(ReadGraphImpl graph) { + try { + procedure.finished(); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } - - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - procedure.exception(t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); } -// impl.state.barrier.dec(); - } - }); + @Override + public void exception(ReadGraphImpl graph, Throwable t) { + try { + procedure.exception(t); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } +// impl.state.barrier.dec(); + } + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } final public void forTypes(final ReadGraphImpl impl, final Resource subject, final AsyncProcedure> procedure) { @@ -4383,47 +3495,29 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap assert(procedure != null); final ListenerBase listener = getListenerBase(procedure); + assert(listener == null); InternalProcedure ip = new InternalProcedure() { - AtomicBoolean first = new AtomicBoolean(true); - @Override public void execute(final ReadGraphImpl graph, IntSet set) { - try { - if(first.compareAndSet(true, false)) { - procedure.execute(graph, set); -// impl.state.barrier.dec(this); - } else { - procedure.execute(impl.newRestart(graph), set); - } - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + procedure.execute(graph, set); } @Override public void exception(ReadGraphImpl graph, Throwable t) { - try { - if(first.compareAndSet(true, false)) { - procedure.exception(graph, t); -// impl.state.barrier.dec(this); - } else { - procedure.exception(impl.newRestart(graph), t); - } - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + procedure.exception(graph, t); } }; int sId = querySupport.getId(subject); -// if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(ip, "#Types" + sId); -// else impl.state.barrier.inc(null, null); - - Types.queryEach(impl, sId, this, impl.parent, listener, ip); + try { + QueryCache.runnerTypes(impl, sId, impl.parent, listener, ip); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -4432,53 +3526,16 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap assert(subject != null); - return Types.queryEach2(impl, querySupport.getId(subject), this, impl.parent); + return QueryCacheBase.resultTypes(impl, querySupport.getId(subject), impl.parent, null); } @Override - final public void forRelationInfo(final ReadGraphImpl impl, final Resource subject, final AsyncProcedure procedure) { - + final public RelationInfo getRelationInfo(final ReadGraphImpl impl, final Resource subject) throws DatabaseException { + assert(subject != null); - assert(procedure != null); - - final ListenerBase listener = getListenerBase(procedure); - -// impl.state.barrier.inc(); - - RelationInfoQuery.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, new InternalProcedure() { - - AtomicBoolean first = new AtomicBoolean(true); - - @Override - public void execute(final ReadGraphImpl graph, RelationInfo set) { - try { - if(first.compareAndSet(true, false)) { - procedure.execute(graph, set); -// impl.state.barrier.dec(); - } else { - procedure.execute(impl.newRestart(graph), set); - } - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } - } - - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - if(first.compareAndSet(true, false)) { - procedure.exception(graph, t); -// impl.state.barrier.dec("ReadGraphSupportImpl.1353"); - } else { - procedure.exception(impl.newRestart(graph), t); - } - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } - } - }); + return QueryCache.resultRelationInfoQuery(impl, querySupport.getId(subject), impl.parent, null); } @@ -4490,14 +3547,13 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap final ListenerBase listener = getListenerBase(procedure); -// impl.state.barrier.inc(); - - SuperTypes.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, new InternalProcedure() { + try { + QueryCache.runnerSuperTypes(impl, querySupport.getId(subject), impl.parent, listener, new InternalProcedure() { - AtomicBoolean first = new AtomicBoolean(true); + AtomicBoolean first = new AtomicBoolean(true); - @Override - public void execute(final ReadGraphImpl graph, IntSet set) { + @Override + public void execute(final ReadGraphImpl graph, IntSet set) { // final HashSet result = new HashSet(); // set.forEach(new TIntProcedure() { // @@ -4508,33 +3564,36 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // } // // }); - try { - if(first.compareAndSet(true, false)) { - procedure.execute(graph, set); + try { + if(first.compareAndSet(true, false)) { + procedure.execute(graph, set); // impl.state.barrier.dec(); - } else { - procedure.execute(impl.newRestart(graph), set); + } else { + procedure.execute(impl.newRestart(graph), set); + } + } catch (Throwable t2) { + Logger.defaultLogError(t2); } - } catch (Throwable t2) { - Logger.defaultLogError(t2); } - } - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - if(first.compareAndSet(true, false)) { - procedure.exception(graph, t); + @Override + public void exception(ReadGraphImpl graph, Throwable t) { + try { + if(first.compareAndSet(true, false)) { + procedure.exception(graph, t); // impl.state.barrier.dec(); - } else { - procedure.exception(impl.newRestart(graph), t); + } else { + procedure.exception(impl.newRestart(graph), t); + } + } catch (Throwable t2) { + Logger.defaultLogError(t2); } - } catch (Throwable t2) { - Logger.defaultLogError(t2); } - } - }); + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -4585,7 +3644,13 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(ip, "#DirectSuperRelations#" + sId); // else impl.state.barrier.inc(null, null); - DirectSuperRelations.queryEach(impl, sId, this, impl.parent, listener, ip); + try { + QueryCache.runnerDirectSuperRelations(impl, sId, impl.parent, listener, ip); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } + +// DirectSuperRelations.queryEach(impl, sId, this, impl.parent, listener, ip); } @@ -4650,31 +3715,31 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(ip, "#SuperRelations#" + sId); // else impl.state.barrier.inc(null, null); - SuperRelations.queryEach(impl, sId, this, impl.parent, listener, ip); + try { + QueryCache.runnerSuperRelations(impl, sId, impl.parent, listener, ip); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } final public byte[] getValue(final ReadGraphImpl impl, final Resource subject) throws DatabaseException { - - int sId = querySupport.getId(subject); - return ValueQuery.queryEach(impl, sId, impl.parent); - + return getValue(impl, querySupport.getId(subject)); } final public byte[] getValue(final ReadGraphImpl impl, final int subject) throws DatabaseException { - - return ValueQuery.queryEach(impl, subject, impl.parent); - + return QueryCache.resultValueQuery(impl, subject, impl.parent, null); } @Override - final public byte[] forValue(final ReadGraphImpl impl, final Resource subject, final AsyncProcedure procedure) { + final public void forValue(final ReadGraphImpl impl, final Resource subject, final AsyncProcedure procedure) { assert(subject != null); + assert(procedure != null); int sId = querySupport.getId(subject); - if(procedure != null) { +// if(procedure != null) { final ListenerBase listener = getListenerBase(procedure); @@ -4715,13 +3780,19 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(ip, "#Value" + sId); // else impl.state.barrier.inc(null, null); - return ValueQuery.queryEach(impl, sId, impl.parent, listener, ip); - - } else { + try { + QueryCache.runnerValueQuery(impl, sId, impl.parent, listener, ip); + } catch (DatabaseException e) { + throw new IllegalStateException("Internal error"); + } - return ValueQuery.queryEach(impl, sId, impl.parent, null, null); - - } +// } else { +// +// return QueryCacheBase.runnerValueQuery(impl, sId, impl.parent, null, null); +// +// } +// +// throw new IllegalStateException("Internal error"); } @@ -4774,7 +3845,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(ip, "#Value" + sId); // else impl.state.barrier.inc(null, null); - ValueQuery.queryEach(impl, sId, impl.parent, listener, ip); + try { + QueryCache.runnerValueQuery(impl, sId, impl.parent, listener, ip); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } else { @@ -4798,7 +3873,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap int sId = querySupport.getId(subject); - ValueQuery.queryEach(impl, sId, impl.parent, listener, ip); + try { + QueryCache.runnerValueQuery(impl, sId, impl.parent, listener, ip); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -4878,7 +3957,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(ip, "#DirectObjects#" + sId); // else impl.state.barrier.inc(null, null); - Objects.runner(impl, sId, getInverseOf(), impl.parent, listener, ip); + try { + QueryCache.runnerObjects(impl, sId, getInverseOf(), impl.parent, listener, ip); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -4928,29 +4011,33 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // impl.state.barrier.inc(); - forBuiltin(impl, id, impl.parent, new InternalProcedure() { + try { + forBuiltin(impl, id, impl.parent, new InternalProcedure() { - @Override - public void execute(ReadGraphImpl graph, Integer result) { - try { - procedure.execute(graph, querySupport.getResource(result)); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + @Override + public void execute(ReadGraphImpl graph, Integer result) { + try { + procedure.execute(graph, querySupport.getResource(result)); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } + } - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - procedure.exception(graph, t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + @Override + public void exception(ReadGraphImpl graph, Throwable t) { + try { + procedure.exception(graph, t); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } + } - }); + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -4962,39 +4049,13 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap final ListenerBase listener = getListenerBase(procedure); -// impl.state.barrier.inc(); - - DirectPredicates.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, new IntProcedure() { - - boolean found = false; - - @Override - public void execute(ReadGraphImpl graph, int object) { - found = true; - } - - @Override - public void finished(ReadGraphImpl graph) { - try { - procedure.execute(graph, found); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } -// impl.state.barrier.dec(); - } - - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - procedure.exception(graph, t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } -// impl.state.barrier.dec(); - } - - }); - + try { + IntSet result = QueryCache.resultDirectPredicates(impl, querySupport.getId(subject), impl.parent, listener); + procedure.execute(impl, !result.isEmpty()); + } catch (DatabaseException e) { + procedure.exception(impl, e); + } + } @Override @@ -5094,30 +4155,34 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap // impl.state.barrier.inc(); - ValueQuery.queryEach(impl, querySupport.getId(subject), impl.parent, listener, new InternalProcedure() { + try { + QueryCache.runnerValueQuery(impl, querySupport.getId(subject), impl.parent, listener, new InternalProcedure() { - @Override - public void execute(ReadGraphImpl graph, byte[] object) { - boolean result = object != null; - try { - procedure.execute(graph, result); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + @Override + public void execute(ReadGraphImpl graph, byte[] object) { + boolean result = object != null; + try { + procedure.execute(graph, result); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } - - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - procedure.exception(graph, t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); } + + @Override + public void exception(ReadGraphImpl graph, Throwable t) { + try { + procedure.exception(graph, t); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } + } - }); + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } } @@ -5129,149 +4194,155 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap final ListenerBase listener = getListenerBase(procedure); -// impl.state.barrier.inc(); - - OrderedSet.queryEach(impl, querySupport.getId(subject), this, impl.parent, listener, new IntProcedure() { + try { + + QueryCache.runnerOrderedSet(impl, querySupport.getId(subject), impl.parent, listener, new IntProcedure() { - @Override - public void exception(ReadGraphImpl graph, Throwable t) { - try { - procedure.exception(graph, t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } + @Override + public void exception(ReadGraphImpl graph, Throwable t) { + try { + procedure.exception(graph, t); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } // impl.state.barrier.dec(); - } - - @Override - public void execute(ReadGraphImpl graph, int i) { - try { - procedure.execute(graph, querySupport.getResource(i)); - } catch (Throwable t2) { - Logger.defaultLogError(t2); } - } - @Override - public void finished(ReadGraphImpl graph) { - try { - procedure.finished(graph); - } catch (Throwable t2) { - Logger.defaultLogError(t2); + @Override + public void execute(ReadGraphImpl graph, int i) { + try { + procedure.execute(graph, querySupport.getResource(i)); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } } -// impl.state.barrier.dec(); - } - - }); - - } - - @Override - final public void query(final ReadGraphImpl impl, final AsyncRead request, final CacheEntry parent, final AsyncProcedure procedure, ListenerBase listener) { - - assert(request != null); - assert(procedure != null); - -// if(AsyncBarrierImpl.BOOKKEEPING) impl.state.barrier.inc(request, "#" + request.toString() + ".1999"); -// else impl.state.barrier.inc(null, null); - - runAsyncRead(impl, request, parent, listener, procedure); - - } - @Override - final public T tryQuery(final ReadGraphImpl graph, final Read request) throws DatabaseException { - - assert(graph != null); - assert(request != null); + @Override + public void finished(ReadGraphImpl graph) { + try { + procedure.finished(graph); + } catch (Throwable t2) { + Logger.defaultLogError(t2); + } +// impl.state.barrier.dec(); + } - final ReadEntry entry = readMap.get(request); - if(entry != null && entry.isReady()) { - return (T)entry.get(graph, this, null); - } else { - return request.perform(graph); + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); } } - final public T tryQuery(final ReadGraphImpl graph, final ExternalRead request) throws DatabaseException { - - assert(graph != null); - assert(request != null); - - final ExternalReadEntry entry = externalReadMap.get(request); - if(entry != null && entry.isReady()) { - if(entry.isExcepted()) { - Throwable t = (Throwable)entry.getResult(); - if(t instanceof DatabaseException) throw (DatabaseException)t; - else throw new DatabaseException(t); - } else { - return (T)entry.getResult(); - } - } else { - - final DataContainer result = new DataContainer(); - final DataContainer exception = new DataContainer(); - - request.register(graph, new Listener() { - - @Override - public void exception(Throwable t) { - exception.set(t); - } - - @Override - public void execute(T t) { - result.set(t); - } - - @Override - public boolean isDisposed() { - return true; - } - - }); - - Throwable t = exception.get(); - if(t != null) { - if(t instanceof DatabaseException) throw (DatabaseException)t; - else throw new DatabaseException(t); - } - - return result.get(); +// @Override +// final public void query(final ReadGraphImpl impl, final AsyncRead request, final CacheEntry parent, final AsyncProcedure procedure, ListenerBase listener) throws DatabaseException { +// +// assert(request != null); +// assert(procedure != null); +// +// QueryCache.runnerAsyncReadEntry(impl, request, parent, listener, procedure); +// +// } - } +// @Override +// final public T tryQuery(final ReadGraphImpl graph, final Read request) throws DatabaseException { +// +// assert(graph != null); +// assert(request != null); +// +// final ReadEntry entry = (ReadEntry)cache.getCached(request); +// if(entry != null && entry.isReady()) { +// return (T)entry.get(graph, this, null); +// } else { +// return request.perform(graph); +// } +// +// } - } +// final public T tryQuery(final ReadGraphImpl graph, final ExternalRead request) throws DatabaseException { +// +// assert(graph != null); +// assert(request != null); +// +// final ExternalReadEntry entry = cache.externalReadMap.get(request); +// if(entry != null && entry.isReady()) { +// if(entry.isExcepted()) { +// Throwable t = (Throwable)entry.getResult(); +// if(t instanceof DatabaseException) throw (DatabaseException)t; +// else throw new DatabaseException(t); +// } else { +// return (T)entry.getResult(); +// } +// } else { +// +// final DataContainer result = new DataContainer(); +// final DataContainer exception = new DataContainer(); +// +// request.register(graph, new Listener() { +// +// @Override +// public void exception(Throwable t) { +// exception.set(t); +// } +// +// @Override +// public void execute(T t) { +// result.set(t); +// } +// +// @Override +// public boolean isDisposed() { +// return true; +// } +// +// }); +// +// Throwable t = exception.get(); +// if(t != null) { +// if(t instanceof DatabaseException) throw (DatabaseException)t; +// else throw new DatabaseException(t); +// } +// +// return result.get(); +// +// } +// +// } - @Override - final public void tryQuery(final ReadGraphImpl graph, final AsyncRead request, AsyncProcedure procedure) { - - assert(graph != null); - assert(request != null); - - final AsyncReadEntry entry = asyncReadMap.get(request); - if(entry != null && entry.isReady()) { - if(entry.isExcepted()) { - procedure.exception(graph, (Throwable)entry.getResult()); - } else { - procedure.execute(graph, (T)entry.getResult()); - } - } else { - request.perform(graph, procedure); - } - - } +// @Override +// final public void tryQuery(final ReadGraphImpl graph, final AsyncRead request, AsyncProcedure procedure) { +// +// assert(graph != null); +// assert(request != null); +// +// final AsyncReadEntry entry = cache.asyncReadMap.get(request); +// if(entry != null && entry.isReady()) { +// if(entry.isExcepted()) { +// procedure.exception(graph, (Throwable)entry.getResult()); +// } else { +// procedure.execute(graph, (T)entry.getResult()); +// } +// } else { +// request.perform(graph, procedure); +// } +// +// } @Override - final public void query(final ReadGraphImpl impl, final MultiRead request, final CacheEntry parent, final AsyncMultiProcedure procedure, ListenerBase listener) { + final public void query(final ReadGraphImpl impl, final MultiRead request, final CacheEntry parent, final SyncMultiProcedure procedure, ListenerBase listener) { assert(request != null); assert(procedure != null); -// impl.state.barrier.inc(null, null); + try { - queryMultiRead(impl, request, parent, listener, procedure); + queryMultiRead(impl, request, parent, listener, procedure); + + } catch (DatabaseException e) { + + throw new IllegalStateException(e); + + } } @@ -5329,40 +4400,48 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } - @Override - final public void query(final ReadGraphImpl impl, final ExternalRead request, final CacheEntry parent, final Procedure procedure, ListenerBase listener) { - - assert(request != null); - assert(procedure != null); - - queryPrimitiveRead(impl, request, parent, listener, new Procedure() { - - @Override - public void execute(T result) { - try { - procedure.execute(result); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } - } - - @Override - public String toString() { - return procedure.toString(); - } - - @Override - public void exception(Throwable t) { - try { - procedure.exception(t); - } catch (Throwable t2) { - Logger.defaultLogError(t2); - } - } - - }); - - } +// @Override +// final public void query(final ReadGraphImpl impl, final ExternalRead request, final CacheEntry parent, final Procedure procedure, ListenerBase listener) throws DatabaseException { +// +// assert(request != null); +// assert(procedure != null); +// +// try { +// +// queryPrimitiveRead(impl, request, parent, listener, new AsyncProcedure() { +// +// @Override +// public String toString() { +// return procedure.toString(); +// } +// +// @Override +// public void execute(AsyncReadGraph graph, T result) { +// try { +// procedure.execute(result); +// } catch (Throwable t2) { +// Logger.defaultLogError(t2); +// } +// } +// +// @Override +// public void exception(AsyncReadGraph graph, Throwable throwable) { +// try { +// procedure.exception(throwable); +// } catch (Throwable t2) { +// Logger.defaultLogError(t2); +// } +// } +// +// }); +// +// } catch (DatabaseException e) { +// +// throw new IllegalStateException(e); +// +// } +// +// } @Override public VirtualGraph getProvider(Resource subject, Resource predicate, Resource object) { @@ -5408,5 +4487,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } return L0; } + + public static ThreadLocal thread = new ThreadLocal() { + protected Integer initialValue() { + return -1; + } + }; }