1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.db.impl.query;
14 import java.util.ArrayList;
15 import java.util.Iterator;
17 import org.simantics.db.RelationInfo;
18 import org.simantics.db.exception.DatabaseException;
19 import org.simantics.db.impl.DebugPolicy;
20 import org.simantics.db.impl.graph.ReadGraphImpl;
21 import org.simantics.db.impl.procedure.InternalProcedure;
22 import org.simantics.db.impl.query.QueryProcessor.Runner2Procedure;
23 import org.simantics.db.procedure.ListenerBase;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
27 abstract public class CacheEntryBase<Procedure> extends CacheEntry<Procedure> {
29 private static final Logger LOGGER = LoggerFactory.getLogger(CacheEntryBase.class);
31 // Default level is something that is not quite a prospect but still allows for ordering within CacheCollectionResult
32 public static final short UNDEFINED_LEVEL = 5;
34 public short level = UNDEFINED_LEVEL;
36 public int GCStatus = 0;
38 final public static CacheEntryBase[] NONE = new CacheEntryBase[0];
40 static Object NO_RESULT = new Object();
41 static protected Object INVALID_RESULT = new Object();
44 // static protected Object FRESH = new Object() { public String toString() { return "CREATED"; }};
45 // Result is computed - no exception
46 static protected Object READY = new Object() { public String toString() { return "READY"; }};
47 // Computation is under way
48 static protected Object PENDING = new Object() { public String toString() { return "PENDING"; }};
49 // Entry is discarded and is waiting for garbage collect
50 static protected Object DISCARDED = new Object() { public String toString() { return "DISCARDED"; }};
51 // The result has been invalidated
52 static protected Object REQUIRES_COMPUTATION = new Object() { public String toString() { return "REFUTED"; }};
53 // The computation has excepted - the exception is in the result
54 static protected Object EXCEPTED = new Object() { public String toString() { return "EXCEPTED"; }};
56 // This indicates the status of the entry
57 public Object statusOrException = REQUIRES_COMPUTATION;
59 private CacheEntry p1 = null;
60 private Object p2OrParents = null;
65 final public int hashCode() {
66 if(hash == 0) hash = makeHash();
70 abstract int makeHash();
72 // This can be tested to see if the result is finished
73 private Object result = NO_RESULT;
75 final public boolean isFresh() {
76 return REQUIRES_COMPUTATION == statusOrException;
79 public void setReady() {
80 statusOrException = READY;
84 final public boolean isReady() {
85 return READY == statusOrException || EXCEPTED == statusOrException;
89 public void discard() {
90 if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: discarded " + this);
91 statusOrException = DISCARDED;
95 final public boolean isDiscarded() {
96 return DISCARDED == statusOrException;
100 final public void refute() {
101 if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: refuted " + this);
102 statusOrException = REQUIRES_COMPUTATION;
106 final public boolean isRefuted() {
107 return REQUIRES_COMPUTATION == statusOrException;
111 final public void except(Throwable t) {
112 if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: excepted " + this);
113 if(statusOrException != DISCARDED) {
114 statusOrException = EXCEPTED;
117 LOGGER.warn("Cache entry got excepted status after being discarded: " + getClass().getSimpleName(), t);
122 final public void checkAndThrow() throws DatabaseException {
124 Throwable throwable = (Throwable)result;
125 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
126 else throw new DatabaseException(throwable);
131 final public boolean isExcepted() {
132 return EXCEPTED == statusOrException;
136 final public void setPending() {
137 statusOrException = PENDING;
141 final public boolean isPending() {
142 return PENDING == statusOrException;
145 final public boolean requiresComputation() {
146 return REQUIRES_COMPUTATION == statusOrException;
149 final public boolean assertPending() {
150 boolean result = isPending();
152 LOGGER.warn("Assertion failed, expected pending, got " + statusOrException);
157 final public boolean assertNotPending() {
158 boolean result = !isPending();
160 new Exception(this + ": Assertion failed, expected not pending, got " + statusOrException).printStackTrace();
165 final public boolean assertNotDiscarded() {
166 boolean result = !isDiscarded();
168 new Exception(this + ": Assertion failed, expected not discarded, got " + statusOrException).printStackTrace();
174 public void setResult(Object result) {
175 this.result = result;
178 @SuppressWarnings("unchecked")
180 final public <T> T getResult() {
181 assert(statusOrException != DISCARDED);
186 public void clearResult(QuerySupport support) {
187 setResult(NO_RESULT);
191 final public void addParent(CacheEntry entry) {
193 assert(entry != null);
198 if(p2OrParents == entry) {
203 } else if(p2OrParents == null) {
205 } else if(p2OrParents instanceof QueryIdentityHashSet) {
206 ((QueryIdentityHashSet)p2OrParents).add(entry);
207 ((QueryIdentityHashSet)p2OrParents).purge();
209 CacheEntry tmp = (CacheEntry)p2OrParents;
210 p2OrParents = new QueryIdentityHashSet(2);
211 ((QueryIdentityHashSet)p2OrParents).add(tmp);
212 ((QueryIdentityHashSet)p2OrParents).add(entry);
218 CacheEntry pruneFirstParents() {
225 if(!p1.isDiscarded()) {
227 // First parent is still active
235 // First parent is discarded => look for more parents
236 if(p2OrParents instanceof QueryIdentityHashSet) {
238 QueryIdentityHashSet set = (QueryIdentityHashSet)p2OrParents;
239 CacheEntry entry = set.removeDiscarded();
240 if(entry == null) p2OrParents = null;
244 } else if(p2OrParents instanceof CacheEntry) {
246 CacheEntry entry = (CacheEntry)p2OrParents;
247 if(entry.isDiscarded()) {
248 // Second entry is also discarded => all empty
269 final public void removeParent(CacheEntry entry) {
272 if(p2OrParents != null) throw new Error("CacheEntryBase.removeParent: corrupted parents (p1 == null, while p2OrParents != null).");
273 else throw new Error("CacheEntryBase.removeParent: no parents.");
276 if(p2OrParents == null) {
278 } else if(p2OrParents instanceof QueryIdentityHashSet) {
279 QueryIdentityHashSet set = (QueryIdentityHashSet)p2OrParents;
280 int size = set.size();
284 } else if (size == 1) {
285 CacheEntry next = set.iterator().next();
288 } else if(set.size() == 2) {
289 Iterator<CacheEntry> iterator = set.iterator();
290 p1 = iterator.next();
291 p2OrParents = iterator.next();
293 p1 = set.iterator().next();
297 p1 = (CacheEntry)p2OrParents;
301 } else if(p2OrParents.getClass() == QueryIdentityHashSet.class) {
303 QueryIdentityHashSet set = (QueryIdentityHashSet)p2OrParents;
304 boolean success = set.remove(entry);
306 throw new Error("CacheEntryBase.removeParent: parent was not found.");
308 assert(set.size() >= 1);
309 if(set.size() == 1) {
310 p2OrParents = set.iterator().next();
314 if(p2OrParents == entry) {
317 throw new Error("CacheEntryBase.removeParent: had 2 parents but neither was removed.");
323 final public boolean hasParents() {
324 assert(statusOrException != DISCARDED);
329 final public Iterable<CacheEntry<?>> getParents(QueryProcessor processor) {
331 ArrayList<CacheEntry<?>> result = new ArrayList<CacheEntry<?>>();
332 if(p1 != null) result.add(p1);
333 if(p2OrParents != null) {
334 if(p2OrParents instanceof QueryIdentityHashSet) {
335 for(CacheEntry entry : (QueryIdentityHashSet)p2OrParents) {
339 result.add((CacheEntry)p2OrParents);
342 fillImpliedParents(processor, result);
348 CacheEntry getFirstParent(QueryProcessor processor) {
353 boolean moreThanOneParent(QueryProcessor processor) {
354 return p2OrParents != null;
358 int parentCount(QueryProcessor processor) {
359 if(p2OrParents != null) {
360 if(p2OrParents instanceof QueryIdentityHashSet) {
361 return ((QueryIdentityHashSet)p2OrParents).size()+1;
366 return p1 != null ? 1 : 0;
371 protected void fillImpliedParents(QueryProcessor processor, ArrayList<CacheEntry<?>> result) {
374 protected String internalError() {
375 return toString() + " " + statusOrException + " " + result;
379 protected boolean handleException(ReadGraphImpl graph, IntProcedure procedure) throws DatabaseException {
381 procedure.exception(graph, (Throwable)getResult());
388 protected boolean handleException(ReadGraphImpl graph, TripleIntProcedure procedure) throws DatabaseException {
390 procedure.exception(graph, (Throwable)getResult());
397 protected <T> boolean handleException(ReadGraphImpl graph, InternalProcedure<T> procedure) throws DatabaseException {
399 procedure.exception(graph, (Throwable)getResult());
407 boolean isImmutable(ReadGraphImpl graph) throws DatabaseException {
412 boolean shouldBeCollected() {
422 short setLevel(short level) {
423 short existing = this.level;
429 void prepareRecompute(QuerySupport querySupport) {
431 clearResult(querySupport);
440 int setGCStatus(int status) {
446 void setGCStatusFlag(int flag, boolean value) {
455 public Object getOriginalRequest() {
456 // This is the original request for all built-in queries
460 public CacheEntryBase() {
463 abstract public Object compute(ReadGraphImpl graph, Procedure procedure) throws DatabaseException;