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.AsyncReadGraph;
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.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
25 abstract public class CacheEntryBase extends CacheEntry {
27 private static final Logger LOGGER = LoggerFactory.getLogger(CacheEntryBase.class);
29 // Default level is something that is not quite a prospect but still allows for ordering within CacheCollectionResult
30 public static final short UNDEFINED_LEVEL = 5;
32 public short level = UNDEFINED_LEVEL;
34 public int GCStatus = 0;
36 final public static CacheEntryBase[] NONE = new CacheEntryBase[0];
38 static private Object NO_RESULT = new Object();
39 static protected Object INVALID_RESULT = new Object();
42 static protected Object FRESH = new Object() { public String toString() { return "CREATED"; }};
43 // Result is computed - no exception
44 static protected Object READY = new Object() { public String toString() { return "READY"; }};
45 // Computation is under way
46 static protected Object PENDING = new Object() { public String toString() { return "PENDING"; }};
47 // Entry is discarded and is waiting for garbage collect
48 static protected Object DISCARDED = new Object() { public String toString() { return "DISCARDED"; }};
49 // The result has been invalidated
50 static protected Object REFUTED = new Object() { public String toString() { return "REFUTED"; }};
51 // The computation has excepted - the exception is in the result
52 static protected Object EXCEPTED = new Object() { public String toString() { return "EXCEPTED"; }};
54 // This indicates the status of the entry
55 public Object statusOrException = FRESH;
57 private CacheEntry p1 = null;
58 private Object p2OrParents = null;
63 final public int hashCode() {
64 if(hash == 0) hash = makeHash();
68 abstract int makeHash();
70 // This can be tested to see if the result is finished
71 private Object result = NO_RESULT;
73 final public boolean isFresh() {
74 return FRESH == statusOrException;
77 public void setReady() {
78 statusOrException = READY;
82 final public boolean isReady() {
83 return READY == statusOrException || EXCEPTED == statusOrException;
87 public void discard() {
88 if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: discarded " + this);
89 statusOrException = DISCARDED;
93 final public boolean isDiscarded() {
94 return DISCARDED == statusOrException;
98 final public void refute() {
99 if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: refuted " + this);
100 statusOrException = REFUTED;
104 final public boolean isRefuted() {
105 return REFUTED == statusOrException;
109 final public void except(Throwable t) {
110 if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: excepted " + this);
111 if(statusOrException != DISCARDED) {
112 statusOrException = EXCEPTED;
115 LOGGER.warn("Cache entry got excepted status after being discarded: " + getClass().getSimpleName(), t);
120 final public void checkAndThrow() throws DatabaseException {
122 Throwable throwable = (Throwable)result;
123 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
124 else throw new DatabaseException(throwable);
129 final public boolean isExcepted() {
130 return EXCEPTED == statusOrException;
134 final public void setPending() {
135 statusOrException = PENDING;
139 final public boolean isPending() {
140 return PENDING == statusOrException;
143 final public boolean assertPending() {
144 boolean result = isPending();
146 LOGGER.warn("Assertion failed, expected pending, got " + statusOrException);
151 final public boolean assertNotPending() {
152 boolean result = !isPending();
154 new Exception(this + ": Assertion failed, expected not pending, got " + statusOrException).printStackTrace();
159 final public boolean assertNotDiscarded() {
160 boolean result = !isDiscarded();
162 new Exception(this + ": Assertion failed, expected not discarded, got " + statusOrException).printStackTrace();
168 public void setResult(Object result) {
169 this.result = result;
172 @SuppressWarnings("unchecked")
174 final public <T> T getResult() {
175 assert(statusOrException != DISCARDED);
180 public void clearResult(QuerySupport support) {
181 setResult(NO_RESULT);
185 final public void addParent(CacheEntry entry) {
187 assert(entry != null);
192 if(p2OrParents == entry) {
197 } else if(p2OrParents == null) {
199 } else if(p2OrParents instanceof QueryIdentityHashSet) {
200 ((QueryIdentityHashSet)p2OrParents).add(entry);
201 ((QueryIdentityHashSet)p2OrParents).purge();
203 CacheEntry tmp = (CacheEntry)p2OrParents;
204 p2OrParents = new QueryIdentityHashSet(2);
205 ((QueryIdentityHashSet)p2OrParents).add(tmp);
206 ((QueryIdentityHashSet)p2OrParents).add(entry);
212 CacheEntry pruneFirstParents() {
219 if(!p1.isDiscarded()) {
221 // First parent is still active
229 // First parent is discarded => look for more parents
230 if(p2OrParents instanceof QueryIdentityHashSet) {
232 QueryIdentityHashSet set = (QueryIdentityHashSet)p2OrParents;
233 CacheEntry entry = set.removeDiscarded();
234 if(entry == null) p2OrParents = null;
238 } else if(p2OrParents instanceof CacheEntry) {
240 CacheEntry entry = (CacheEntry)p2OrParents;
241 if(entry.isDiscarded()) {
242 // Second entry is also discarded => all empty
263 final public void removeParent(CacheEntry entry) {
266 if(p2OrParents != null) throw new Error("CacheEntryBase.removeParent: corrupted parents (p1 == null, while p2OrParents != null).");
267 else throw new Error("CacheEntryBase.removeParent: no parents.");
270 if(p2OrParents == null) {
272 } else if(p2OrParents instanceof QueryIdentityHashSet) {
273 QueryIdentityHashSet set = (QueryIdentityHashSet)p2OrParents;
274 int size = set.size();
278 } else if (size == 1) {
279 CacheEntry next = set.iterator().next();
282 } else if(set.size() == 2) {
283 Iterator<CacheEntry> iterator = set.iterator();
284 p1 = iterator.next();
285 p2OrParents = iterator.next();
287 p1 = set.iterator().next();
291 p1 = (CacheEntry)p2OrParents;
295 } else if(p2OrParents.getClass() == QueryIdentityHashSet.class) {
297 QueryIdentityHashSet set = (QueryIdentityHashSet)p2OrParents;
298 boolean success = set.remove(entry);
300 throw new Error("CacheEntryBase.removeParent: parent was not found.");
302 assert(set.size() >= 1);
303 if(set.size() == 1) {
304 p2OrParents = set.iterator().next();
308 if(p2OrParents == entry) {
311 throw new Error("CacheEntryBase.removeParent: had 2 parents but neither was removed.");
317 final public boolean hasParents() {
318 assert(statusOrException != DISCARDED);
323 final public Iterable<CacheEntry> getParents(QueryProcessor processor) {
325 ArrayList<CacheEntry> result = new ArrayList<CacheEntry>();
326 if(p1 != null) result.add(p1);
327 if(p2OrParents != null) {
328 if(p2OrParents instanceof QueryIdentityHashSet) {
329 for(CacheEntry entry : (QueryIdentityHashSet)p2OrParents) {
333 result.add((CacheEntry)p2OrParents);
336 fillImpliedParents(processor, result);
342 CacheEntry getFirstParent(QueryProcessor processor) {
347 boolean moreThanOneParent(QueryProcessor processor) {
348 return p2OrParents != null;
352 int parentCount(QueryProcessor processor) {
353 if(p2OrParents != null) {
354 if(p2OrParents instanceof QueryIdentityHashSet) {
355 return ((QueryIdentityHashSet)p2OrParents).size()+1;
360 return p1 != null ? 1 : 0;
365 protected void fillImpliedParents(QueryProcessor processor, ArrayList<CacheEntry> result) {
369 protected String internalError() {
370 return toString() + " " + statusOrException + " " + result;
374 protected boolean handleException(ReadGraphImpl graph, IntProcedure procedure) {
376 procedure.exception(graph, (Throwable)getResult());
383 protected boolean handleException(ReadGraphImpl graph, TripleIntProcedure procedure) {
385 procedure.exception(graph, (Throwable)getResult());
392 protected <T> boolean handleException(ReadGraphImpl graph, InternalProcedure<T> procedure) {
394 procedure.exception(graph, (Throwable)getResult());
402 boolean isImmutable(ReadGraphImpl graph) throws DatabaseException {
407 boolean shouldBeCollected() {
417 short setLevel(short level) {
418 short existing = this.level;
424 void prepareRecompute(QuerySupport querySupport) {
426 clearResult(querySupport);
439 int setGCStatus(int status) {
445 void setGCStatusFlag(int flag, boolean value) {
454 public Object getOriginalRequest() {
455 // This is the original request for all built-in queries
459 // abstract public void addOrSet(AsyncReadGraph graph, Object item);
460 // abstract public void except(AsyncReadGraph graph, Throwable t);
462 //abstract public void perform(AsyncReadGraph graph, Object query, Object procedure);