]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.procore/src/fi/vtt/simantics/procore/internal/ClusterTable.java
5daf534fef481ca3e6b3bd43dcf637d82e2bb4ef
[simantics/platform.git] / bundles / org.simantics.db.procore / src / fi / vtt / simantics / procore / internal / ClusterTable.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package fi.vtt.simantics.procore.internal;
13
14 import java.io.File;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.Map;
19 import java.util.TreeMap;
20 import java.util.concurrent.Semaphore;
21 import java.util.concurrent.atomic.AtomicLong;
22 import java.util.function.Consumer;
23
24 import org.simantics.databoard.Bindings;
25 import org.simantics.db.ClusterCreator;
26 import org.simantics.db.Database;
27 import org.simantics.db.Database.Session.ClusterChanges;
28 import org.simantics.db.DevelopmentKeys;
29 import org.simantics.db.SessionVariables;
30 import org.simantics.db.common.utils.Logger;
31 import org.simantics.db.exception.ClusterDoesNotExistException;
32 import org.simantics.db.exception.DatabaseException;
33 import org.simantics.db.exception.ResourceNotFoundException;
34 import org.simantics.db.exception.RuntimeDatabaseException;
35 import org.simantics.db.impl.ClusterBase;
36 import org.simantics.db.impl.ClusterI;
37 import org.simantics.db.impl.ClusterSupport;
38 import org.simantics.db.impl.ClusterTraitsBase;
39 import org.simantics.db.impl.IClusterTable;
40 import org.simantics.db.impl.graph.WriteGraphImpl;
41 import org.simantics.db.impl.query.QueryProcessor;
42 import org.simantics.db.procore.cluster.ClusterBig;
43 import org.simantics.db.procore.cluster.ClusterImpl;
44 import org.simantics.db.procore.cluster.ClusterSmall;
45 import org.simantics.db.procore.cluster.ClusterTraits;
46 import org.simantics.db.procore.protocol.Constants;
47 import org.simantics.db.service.ClusterCollectorPolicy;
48 import org.simantics.db.service.ClusterCollectorPolicy.CollectorCluster;
49 import org.simantics.db.service.ClusterUID;
50 import org.simantics.utils.Development;
51
52 import fi.vtt.simantics.procore.DebugPolicy;
53 import fi.vtt.simantics.procore.internal.ClusterControlImpl.ClusterStateImpl;
54 import fi.vtt.simantics.procore.internal.SessionImplSocket.TaskHelper;
55 import gnu.trove.map.hash.TLongIntHashMap;
56 import gnu.trove.map.hash.TLongObjectHashMap;
57 import gnu.trove.procedure.TIntProcedure;
58 import gnu.trove.procedure.TLongObjectProcedure;
59 import gnu.trove.procedure.TObjectProcedure;
60 import gnu.trove.set.hash.TIntHashSet;
61
62 public final class ClusterTable implements IClusterTable {
63
64     private static final boolean VALIDATE_SIZE = false;
65
66     int maximumBytes = 128 * 1024 * 1024;
67     int limit = (int)(0.8*(double)maximumBytes);
68
69     private final AtomicLong timeCounter = new AtomicLong(1);
70
71     final private SessionImplSocket sessionImpl;
72     final private ArrayList<ClusterI> writeOnlyClusters = new ArrayList<ClusterI>();
73     final private TIntHashSet writeOnlyInvalidates = new TIntHashSet();
74     final private static int ARRAY_SIZE = ClusterTraits.getClusterArraySize();
75     final private ClusterImpl[] clusterArray = new ClusterImpl[ARRAY_SIZE];
76     final private Boolean[] immutables = new Boolean[ARRAY_SIZE];
77     final private boolean[] virtuals = new boolean[ARRAY_SIZE];
78     static class ImportanceEntry implements CollectorCluster {
79         final public long importance;
80         final public long clusterId;
81         public ImportanceEntry(ClusterImpl impl) {
82             this(impl.getImportance(), impl.getClusterId());
83         }
84
85         public ImportanceEntry(long importance, long clusterId) {
86             this.importance = importance;
87             this.clusterId = clusterId;
88         }
89         @Override
90         public long getImportance() {
91             return importance;
92         }
93         @Override
94         public long getClusterId() {
95             return clusterId;
96         }
97         @Override
98         public String toString() {
99             return "CID " + clusterId;
100         }
101     }
102     private class Clusters {
103         // This makes sure that non-null values from hashMap.get can be trusted (no unsynchronized rehashes occur)
104         final public TLongObjectHashMap<ClusterImpl> hashMap = new TLongObjectHashMap<ClusterImpl>(2 * ARRAY_SIZE);
105         //private final HashMap<ClusterUID, ClusterImpl> clusterU2I = new HashMap<ClusterUID, ClusterImpl>(); // Maps cluster UID to cluster.
106         private Clusters() {
107             clear();
108         }
109         private void clear() {
110             hashMap.clear();
111           //  clusterU2I.clear();
112             hashMap.put(0, null); // reserved for null value
113           //  clusterU2I.put(ClusterUID.make(0, 0), null);
114         }
115         private int size() {
116             return hashMap.size();
117         }
118         private ClusterImpl getClusterByClusterId(long clusterId) {
119             return hashMap.get(clusterId);
120         }
121         private ClusterImpl getClusterByClusterUID(ClusterUID clusterUID) {
122                 return getClusterByClusterId(clusterUID.second);
123             //return clusterU2I.get(clusterUID);
124         }
125         private ClusterImpl getClusterByClusterUID(long id1, long id2) {
126                 return getClusterByClusterId(id2);
127         }
128         private ClusterImpl makeProxy(long clusterId) {
129             return makeProxy(ClusterUID.make(0, clusterId));
130         }
131         private ClusterImpl makeProxy(ClusterUID clusterUID) {
132             ClusterImpl proxy = hashMap.get(clusterUID.second);
133             if (null != proxy)
134                 return proxy;
135             int clusterKey = hashMap.size();
136             ClusterSmall sentinel = new ClusterSmall(clusterUID, clusterKey, ClusterTable.this, sessionImpl.clusterTranslator);
137             if (sentinel.clusterId != sentinel.clusterUID.second)
138                 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
139             create(sentinel);
140             return sentinel;
141         }
142         private void replace(ClusterImpl proxy) {
143             ClusterImpl old = clusterArray[proxy.clusterKey];
144             create(proxy);
145             if (null != old) {
146                 if (old.clusterKey != proxy.clusterKey)
147                     throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
148                 if (old.clusterId != proxy.clusterId)
149                     throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
150                 if (!old.clusterUID.equals(proxy.clusterUID))
151                     throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
152             }
153         }
154         private ClusterSmall freeProxy(ClusterImpl proxy) {
155             ClusterImpl clusterImpl = hashMap.get(proxy.clusterId);
156             if (null == clusterImpl)
157                 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
158 //            ClusterUID clusterUID = ClusterUID.make(0, proxy.clusterId);
159 //            ClusterImpl clusterImpl2 = clusterU2I.get(clusterUID );
160 //            if (clusterImpl != clusterImpl2)
161 //                throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
162             if (proxy.clusterId != clusterImpl.clusterId)
163                 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
164             if (proxy.clusterKey != clusterImpl.clusterKey)
165                 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
166             ClusterSmall sentinel = new ClusterSmall(makeClusterUID(proxy.clusterId) , proxy.clusterKey, ClusterTable.this, sessionImpl.clusterTranslator);
167             return (ClusterSmall)create(sentinel);
168         }
169         private ClusterImpl create(ClusterImpl clusterImpl) {
170             hashMap.put(clusterImpl.clusterId, clusterImpl);
171 //            clusterU2I.put(clusterImpl.clusterUID, clusterImpl);
172             clusterArray[clusterImpl.clusterKey] = clusterImpl;
173             return clusterImpl;
174         }
175         private void forEachValue(TObjectProcedure<ClusterImpl> procedure) {
176             hashMap.forEachValue(procedure);
177         }
178         private void forEachEntry(TLongObjectProcedure<ClusterImpl> procedure) {
179             hashMap.forEachEntry(procedure);
180         }
181         private ClusterUID makeClusterUID(long clusterId) {
182             return ClusterUID.make(0, clusterId);
183         }
184         private void removeProxy(ClusterImpl proxy) {
185             hashMap.remove(proxy.clusterId);
186             clusterArray[proxy.clusterKey] = null;
187         }
188     }
189     final public TreeMap<Long, CollectorCluster> importanceMap = new TreeMap<Long, CollectorCluster>();
190
191     private ClusterCollectorPolicy collectorPolicy;
192     private boolean dirtySizeInBytes = true;
193     private long sizeInBytes = 0;
194     private final Clusters clusters;
195     ClusterUID makeClusterUID(long clusterId) {
196         return clusters.makeClusterUID(clusterId);
197     }
198     public ClusterUID getClusterUIDByResourceKey(int resourceKey) throws DatabaseException {
199         int clusterKey = ClusterTraits.getClusterKeyFromResourceKey(resourceKey);
200         return clusterArray[clusterKey].clusterUID;
201     }
202     ClusterTable(SessionImplSocket sessionImpl, File folderPath) {
203         this.sessionImpl = sessionImpl;
204         clusters = new Clusters();
205     }
206
207     void dispose() {
208         clusters.clear();
209         importanceMap.clear();
210     }
211
212     public void setCollectorPolicy(ClusterCollectorPolicy policy) {
213         this.collectorPolicy = policy;
214     }
215
216     /**
217      * Sets Cluster Table allocation size by percentage of maximum usable
218      * memory. Allocation is limited between 5% and 50% of maximum memory.
219      *
220      * @param precentage
221      */
222     private void setAllocateSize(double percentage) {
223
224         percentage = Math.max(percentage, 0.05);
225         percentage = Math.min(percentage, 0.5);
226
227         maximumBytes = (int) Math.floor(percentage * Runtime.getRuntime().maxMemory());
228     }
229
230     private double estimateProperAllocation(ClusterCollectorSupport support) {
231         long max = Runtime.getRuntime().maxMemory();
232         long free = Runtime.getRuntime().freeMemory();
233         long total = Runtime.getRuntime().totalMemory();
234         long realFree = max - total + free; // amount of free memory
235         long current = support.getCurrentSize(); // currently allocated cache
236         long inUseTotal = max - realFree; // currently used memory
237         long inUseOther = inUseTotal - current; // memory that the application uses (without the cache)
238         double otherUsePercentage = (double) inUseOther / (double) max; // percentage of memory that the application uses
239         double aimFree = 0.2; // percentage of maximum heap that we try to keep free
240         double estimate = 1.0 - otherUsePercentage - aimFree;
241         estimate = Math.min(estimate, 0.5);
242         estimate = Math.max(estimate, 0.05);
243         // System.out.println("Estimated allocation percentage " + estimate +
244 // " memory stats: max: " + max + ", free: " + realFree + ", inUse: " +
245 // inUseTotal + ", cached: " + current + ", cacheSize: " + maximumBytes);
246         return estimate;
247     }
248
249     void checkCollect() {
250         collector.collect();
251     }
252
253     synchronized ClusterImpl getClusterByClusterId(long clusterId) {
254         return clusters.getClusterByClusterId(clusterId);
255     }
256
257     ClusterBase getClusterByClusterKey(int clusterKey) {
258         return clusterArray[clusterKey];
259     }
260
261     synchronized ClusterImpl makeProxy(ClusterUID clusterUID, long clusterId) {
262         if (clusterUID.second != clusterId)
263             throw new RuntimeDatabaseException("Illegal id for cluster=" + clusterUID + " id=" + clusterId);
264         return clusters.makeProxy(clusterUID);
265     }
266
267     synchronized ClusterImpl makeCluster(long clusterId, boolean writeOnly) {
268         checkCollect();
269         ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
270         if (null != proxy)
271             return proxy;
272         ClusterUID clusterUID = ClusterUID.make(0, clusterId);
273         int clusterKey = clusters.size(); // new key
274         if (writeOnly) {
275             proxy = new ClusterWriteOnly(clusterUID, clusterKey, sessionImpl);
276             writeOnlyClusters.add(proxy);
277             return clusters.create(proxy);
278         } else {
279             //printMaps("makeCluster");
280             ClusterImpl cluster = ClusterImpl.make(clusterUID, clusterKey, sessionImpl.clusterTranslator);
281             clusters.create(cluster);
282             if (!cluster.isLoaded())
283                 Logger.defaultLogError(new Exception("Bug in ClusterTable.makeCluster(long, boolean), cluster not loaded"));
284             importanceMap.put(cluster.getImportance(), new ImportanceEntry(cluster));
285             if (VALIDATE_SIZE)
286                 validateSize("makeCluster");
287             if(collectorPolicy != null) collectorPolicy.added(cluster);
288             return cluster;
289         }
290     }
291
292     synchronized void replaceCluster(ClusterI cluster) {
293         //printMaps("replaceCluster");
294         checkCollect();
295         int clusterKey = cluster.getClusterKey();
296         ClusterI existing = clusterArray[clusterKey];
297         if (existing.hasVirtual())
298             cluster.markVirtual();
299
300         long existingImportance = existing.getImportance();
301         if (existingImportance != 0)
302             importanceMap.remove(existingImportance);
303         if (collectorPolicy != null)
304             collectorPolicy.removed((ClusterImpl)existing);
305
306         //System.out.println("ClusterTable.replace(" + existing + " (I=" + existing.getImportance() + ") => " + cluster + " (I=" + cluster.getImportance() + ")");
307
308         clusters.replace((ClusterImpl)cluster);
309         if (!cluster.isLoaded())
310             Logger.defaultLogError(new Exception("Bug in ClusterTable.replaceCluster(ClusterI), cluster not loaded"));
311
312         importanceMap.put(cluster.getImportance(), new ImportanceEntry((ClusterImpl)cluster));
313         if(collectorPolicy != null) collectorPolicy.added((ClusterImpl)cluster);
314
315         if (!dirtySizeInBytes) {
316             if (existing != cluster) {
317                 adjustCachedSize(-existing.getCachedSize(), existing);
318             }
319             // This will update sizeInBytes through adjustCachedSize
320             cluster.getCachedSize();
321         }
322         if (VALIDATE_SIZE)
323             validateSize("replaceCluster");
324     }
325
326     synchronized void release(CollectorCluster cluster) {
327         importanceMap.remove(cluster.getImportance());
328         release(cluster.getClusterId());
329     }
330
331     synchronized void release(long clusterId) {
332         //System.out.println("ClusterTable.release(" + clusterId + "): " + sizeInBytes);
333         //validateSize();
334         ClusterImpl clusterImpl = clusters.getClusterByClusterId(clusterId);
335         if (null == clusterImpl)
336             return;
337         if(!clusterImpl.isLoaded() || clusterImpl.isEmpty())
338             return;
339         //printMaps("release");
340         clusters.freeProxy(clusterImpl);
341         importanceMap.remove(clusterImpl.getImportance());
342         if (collectorPolicy != null)
343             collectorPolicy.removed(clusterImpl);
344         if (sessionImpl.writeState != null)
345             sessionImpl.clusterStream.flush(clusterImpl.clusterUID);
346         if (!dirtySizeInBytes) {
347             adjustCachedSize(-clusterImpl.getCachedSize(), clusterImpl);
348         }
349         if (VALIDATE_SIZE)
350             validateSize("release");
351     }
352
353     synchronized void compact(long id) {
354         ClusterI impl = clusters.getClusterByClusterId(id);
355         if (impl != null)
356             impl.compact();
357     }
358
359     void updateSize() {
360 // cachedSize = getSizeInBytes();
361     }
362
363     double getLoadProbability() {
364         // This can currently cause stack overflow
365         return 1.0;
366 // if(cachedSize < SLOW_LIMIT) return 1.0;
367 // if(cachedSize > HIGH_LIMIT) return 1e-2;
368 //
369 // double pos = (double)(cachedSize - SLOW_LIMIT) / (double)(HIGH_LIMIT -
370 // SLOW_LIMIT);
371 // double val = 0.1 * ((pos-1) * (pos-1)) + 1e-2;
372 // return val;
373     }
374
375     class SizeProcedure implements TObjectProcedure<ClusterImpl> {
376         public long result = 0;
377
378         @Override
379         public boolean execute(ClusterImpl cluster) {
380             if (cluster != null) {
381                 try {
382                     if (cluster.isLoaded() && !cluster.isEmpty()) {
383                         result += cluster.getCachedSize();
384                     }
385                 } catch (Throwable t) {
386                     Logger.defaultLogError(t);
387                 }
388             }
389             return true;
390         }
391
392         public void clear() {
393             result = 0;
394         }
395
396     };
397
398     private SizeProcedure sizeProcedure = new SizeProcedure();
399     long getSizeInBytes() {
400         if (dirtySizeInBytes) {
401             sizeProcedure.clear();
402             clusters.forEachValue(sizeProcedure);
403             sizeInBytes = sizeProcedure.result;
404             // System.err.println("recomputed size of clusterTable => " + sizeInBytes);
405             setDirtySizeInBytes(false);
406         }
407         return sizeInBytes;
408     }
409
410     public void setDirtySizeInBytes(boolean value) {
411         dirtySizeInBytes = value;
412     }
413
414     ClusterStateImpl getState() {
415         final ClusterStateImpl result = new ClusterStateImpl();
416         clusters.forEachEntry(new TLongObjectProcedure<ClusterImpl>() {
417             @Override
418             public boolean execute(long arg0, ClusterImpl arg1) {
419                 if (arg1 == null)
420                     return true;
421                 if (arg1.isLoaded() && !arg1.isEmpty()) {
422                     result.ids.add(new ImportanceEntry(arg1));
423                 }
424                 return true;
425             }
426         });
427         return result;
428     }
429
430     void restoreState(ClusterStateImpl state) {
431         ClusterStateImpl current = getState();
432         for (CollectorCluster id : current.ids)
433             if (!state.ids.contains(id))
434                 collectorSupport.release(id);
435     }
436
437     class ClusterCollectorImpl implements ClusterCollector {
438
439         final private ClusterCollectorSupport support;
440         private ClusterCollectorPolicy policy;
441         ClusterCollectorImpl(ClusterCollectorSupport support) {
442             this.support = support;
443         }
444
445         ClusterCollectorPolicy setPolicy(ClusterCollectorPolicy newPolicy) {
446
447             ClusterCollectorPolicy oldPolicy = policy;
448             policy = newPolicy;
449
450             if(policy != null) {
451                 for (CollectorCluster id : support.getResidentClusters()) {
452                     policy.added(getClusterByClusterId(id.getClusterId()));
453                 }
454             }
455
456             support.setPolicy(policy);
457
458             return oldPolicy;
459
460         }
461
462         @Override
463         public void collect() {
464
465             if(policy != null) {
466
467                 release(policy.select());
468
469             } else {
470
471                 int size = support.getCurrentSize();
472                 boolean dynamicAllocation = useDynamicAllocation();
473                 if (dynamicAllocation)
474                     setAllocateSize(estimateProperAllocation(support));
475                 if (DebugPolicy.CLUSTER_COLLECTION) {
476                     System.out.println("Cluster collector activated, current size = " + size + " limit = " + maximumBytes);
477                 }
478                 if (dynamicAllocation) {
479                     int collectSize = maximumBytes / 2;
480                     collectSize = Math.min(collectSize, 32 * 1024 * 1024);
481                     // try to keep allocated clusters below the maximum
482                     if (maximumBytes - size > collectSize)
483                         return;
484                     collectSize += size - maximumBytes;
485                     collect(collectSize);
486                 } else {
487                     // try to keep allocated clusters below the maximum
488                     if (size < maximumBytes)
489                         return;
490                     // shave off 20%
491                     collect(size-limit);
492                 }
493
494             }
495
496         }
497
498         private boolean useDynamicAllocation() {
499             return "true".equalsIgnoreCase(System.getProperty("org.simantics.db.cluster.dynamicAlloc"));
500         }
501
502         @Override
503         public void collect(int target) {
504
505             if(policy != null) {
506
507                 release(policy.select(target));
508
509             } else {
510
511                 ArrayList<CollectorCluster> toRelease = new ArrayList<CollectorCluster>();
512
513                 for (CollectorCluster cluster : support.getResidentClusters()) {
514                     target -= support.getClusterSize(cluster);
515                     if (target > 0) {
516                         toRelease.add(cluster);
517                     } else {
518                         break;
519                     }
520                 }
521
522                 release(toRelease);
523
524                 if (DebugPolicy.CLUSTER_COLLECTION) {
525                     System.out.println("Cluster collector finished, current size = " + support.getCurrentSize());
526                 }
527
528             }
529
530         }
531
532         void release(Collection<CollectorCluster> toRelease) {
533             for (CollectorCluster id : toRelease) {
534                 support.release(id);
535             }
536         }
537
538     }
539
540     private ClusterCollectorSupport collectorSupport = new ClusterCollectorSupportImpl(this);
541     ClusterCollectorImpl collector = new ClusterCollectorImpl(collectorSupport);
542
543     void gc() {
544         collector.collect();
545     }
546
547     private long newResourceClusterId = Constants.NewClusterId;
548     public static final int CLUSTER_FILL_SIZE = ClusterTraitsBase.getMaxNumberOfResources();
549
550     /*
551      * Uusi id varataan vasta, kun lis�t��n resurssi => reservedIds sis�lt��
552      * vain jo k�yt�ss� olevia klustereita
553      */
554
555     ClusterImpl getNewResourceCluster(ClusterSupport cs, GraphSession graphSession, boolean writeOnly)
556     throws DatabaseException {
557         ClusterImpl result = null;
558         if (Constants.NewClusterId == newResourceClusterId) {
559             newResourceClusterId = graphSession.newClusterId();
560             result = getClusterByClusterIdOrMake(newResourceClusterId, writeOnly);
561         } else {
562             ClusterImpl cluster = getClusterByClusterIdOrThrow(newResourceClusterId);
563             if (cluster.getNumberOfResources(cs) >= CLUSTER_FILL_SIZE) {
564                 newResourceClusterId = graphSession.newClusterId();
565                 cluster = getClusterByClusterIdOrMake(newResourceClusterId, writeOnly);
566             }
567             result = cluster;
568         }
569         return ensureLoaded(result);
570     }
571
572     void flushCluster(GraphSession graphSession) {
573 // We seem to disagree about this.
574 // graphSession.newClusterId();
575         newResourceClusterId = Constants.NewClusterId;
576     }
577
578     void writeOnlyInvalidate(ClusterI impl) {
579         writeOnlyInvalidates.add(impl.getClusterKey());
580     }
581
582     void removeWriteOnlyClusters() {
583         for (ClusterI proxy : writeOnlyClusters) {
584             if (!(proxy instanceof ClusterImpl))
585                 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
586             clusters.freeProxy((ClusterImpl)proxy);
587         }
588         writeOnlyClusters.clear();
589         writeOnlyInvalidates.forEach(new TIntProcedure() {
590             @Override
591             public boolean execute(int clusterKey) {
592                 ClusterImpl proxy = clusterArray[clusterKey];
593                 ClusterUID clusterUID = proxy.getClusterUID();
594                 System.err.println("writeOnlyInvalidate " + clusterUID);
595                 clusters.freeProxy(proxy);
596                 return true;
597             }
598         });
599         writeOnlyInvalidates.clear();
600     }
601
602     public ClusterImpl getClusterByClusterUID(ClusterUID clusterUID) {
603         synchronized (this) {
604             return clusters.getClusterByClusterUID(clusterUID);
605         }
606     }
607     public int getClusterKeyByClusterUIDOrMakeProxy(ClusterUID clusterUID) {
608         return getClusterKeyByClusterUIDOrMakeProxy(0/*clusterUID.first*/, clusterUID.second);
609     }
610     public int getClusterKeyByClusterUIDOrMakeProxy(long id1, long id2) {
611         return getClusterByClusterUIDOrMakeProxy(id1, id2).clusterKey;
612     }
613     public ClusterImpl getClusterByClusterUIDOrMakeProxy(ClusterUID clusterUID) {
614         synchronized (this) {
615             ClusterImpl clusterImpl = clusters.getClusterByClusterUID(clusterUID);
616             if (null == clusterImpl)
617                 clusterImpl = clusters.makeProxy(clusterUID);
618             return clusterImpl;
619         }
620     }
621     public ClusterImpl getClusterByClusterUIDOrMakeProxy(long id1, long id2) {
622         synchronized (this) {
623             ClusterImpl clusterImpl = clusters.getClusterByClusterUID(id1, id2);
624             if (null == clusterImpl)
625                 clusterImpl = clusters.makeProxy(id2);
626             return clusterImpl;
627         }
628     }
629     ClusterImpl getLoadOrThrow(long clusterId) throws DatabaseException {
630         synchronized (this) {
631             ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
632             int clusterKey = 0;
633             if (proxy != null)
634                 if (proxy.isLoaded())
635                     return proxy;
636                 else
637                     clusterKey = proxy.getClusterKey();
638             try {
639                 if (clusterKey == 0) {
640                     proxy = clusters.makeProxy(clusterId);
641                     clusterKey = proxy.getClusterKey();
642                 }
643                 ClusterImpl ci = tryLoad(clusterId, clusterKey);
644                 if (null == ci)
645                     throw new ResourceNotFoundException(clusterId);
646                 return ci;
647             } catch (ClusterDoesNotExistException t) {
648                 clusters.removeProxy(proxy);
649                 throw t;
650             }
651         }
652     }
653
654     ClusterImpl getClusterByClusterIdOrMake(long clusterId, boolean writeOnly) {
655         synchronized (this) {
656             ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
657             if (proxy != null)
658                 return proxy;
659             else
660                 return makeCluster(clusterId, writeOnly);
661         }
662     }
663     ClusterImpl getClusterByClusterIdOrThrow(long clusterId) {
664         synchronized (this) {
665             ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
666             if (null == proxy)
667                 throw new IllegalArgumentException("Cluster id=" + clusterId + " is not created.");
668             return proxy;
669         }
670     }
671     long getClusterIdOrCreate(ClusterUID clusterUID) {
672         return clusterUID.second;
673     }
674     final long getClusterIdByResourceKey(final int resourceKey)
675     throws DatabaseException {
676         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKey(resourceKey);
677         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
678             throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
679         ClusterI c = clusterArray[clusterKey];
680         if (c == null)
681             throw new RuntimeException("No cluster for key " + resourceKey);
682         return c.getClusterId();
683     }
684     final long getClusterIdByResourceKeyNoThrow(final int resourceKey) {
685         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
686         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey)) {
687             Logger.defaultLogError("Tried to get a persistent cluster for a virtual resource. key=" + resourceKey);
688             return 0;
689         }
690         ClusterI c = clusterArray[clusterKey];
691         if (c == null) {
692             Logger.defaultLogError("No cluster for key " + resourceKey);
693             return 0;
694         }
695         return c.getClusterId();
696     }
697
698     int counter = 0;
699
700     void refresh(long csid, SessionImplSocket session, ClusterUID[] clusterUID) {
701         synchronized (this) {
702             session.flushCounter = 0;
703             session.clusterStream.reallyFlush();
704             ClientChangesImpl cs = new ClientChangesImpl(session);
705             if (session.clientChanges == null)
706                 session.clientChanges = cs;
707             //printMaps("refresh");
708             for (int i=0; i<clusterUID.length; ++i) {
709                 try {
710                     if (DebugPolicy.REPORT_CLUSTER_EVENTS)
711                         System.err.println("cluster=" + clusterUID[i] + " has changed. length=" + clusterUID.length);
712                     ClusterImpl oldCluster = clusters.getClusterByClusterUID(clusterUID[i]);
713                     if (null == oldCluster)
714                         continue;
715                     if (!oldCluster.isLoaded())
716                         continue;
717                     int clusterKey = oldCluster.getClusterKey();
718                     if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
719                         continue;
720                     boolean big = oldCluster instanceof ClusterBig;
721                     boolean small = oldCluster instanceof ClusterSmall;
722                     if (!big && !small)
723                         continue;
724 //                    ClusterImpl newCluster = (ClusterImpl) sessionImpl.graphSession.getClusterImpl(clusterUID[i], clusterKey);
725                     Database.Session dbSession = sessionImpl.graphSession.dbSession;
726                     
727                     ClusterImpl newCluster = dbSession.clone(clusterUID[i], new ClusterCreator() {
728                         
729                         @Override
730                         public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
731                             ClusterSupport support = sessionImpl.clusterTranslator;
732                             try {
733                                 return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
734                             } catch (DatabaseException e) {
735                                 e.printStackTrace();
736                                 return null;
737                             }
738                         }
739                         
740                     });
741                     if (null == newCluster)
742                         continue;
743                     if (DebugPolicy.REPORT_CLUSTER_EVENTS)
744                         System.err.println("cluster=" + newCluster + "  updated.");
745                     importanceMap.remove(oldCluster.getImportance());
746                     if (collectorPolicy != null)
747                         collectorPolicy.removed(oldCluster);
748                     clusters.replace(newCluster);
749                     if (!newCluster.isLoaded())
750                         Logger.defaultLogError(new Exception("Bug in ClusterTable.refresh, cluster not loaded"));
751                     importanceMap.put(newCluster.getImportance(), new ImportanceEntry(newCluster));
752                     if (collectorPolicy != null)
753                         collectorPolicy.added(newCluster);
754                     // Now we have fetched the new cluster but to emulate effects of the changes in it we fetch the cluster changes from server.
755                     refreshCluster(csid, session, oldCluster, clusterUID[i], newCluster.clusterId, clusterKey);
756                 } catch (Throwable t) {
757                     Logger.defaultLogError("Failed to load cluster in refresh.", t);
758                 }
759             }
760             if (VALIDATE_SIZE)
761                 validateSize("refresh");
762             // Fake update of cluster changes.
763             QueryProcessor queryProcessor = session.getQueryProvider2();
764             WriteGraphImpl writer = WriteGraphImpl.create(queryProcessor, session.writeSupport, null);
765             TaskHelper th = null;
766             if (null == session.writeState) {
767                 th = new TaskHelper("Refresh");
768                 session.writeState = new WriteState<Object>(writer, th.writeTraits, th.sema, th.proc);
769                 try {
770                     session.getQueryProvider2().performDirtyUpdates(writer);
771                     session.fireMetadataListeners(writer, cs);
772                     session.getQueryProvider2().performScheduledUpdates(writer);
773                     session.fireReactionsToSynchronize(cs);
774                     session.fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
775                     session.printDiagnostics();
776                 } finally {
777                     if (null != th)
778                         session.writeState = null;
779                     cs.dispose();
780                 }
781             }
782         }
783     }
784     final void refreshCluster(long csid, SessionImplSocket session, ClusterImpl cluster, ClusterUID clusterUID, long clusterId, int clusterKey)
785     throws DatabaseException {
786         if (DebugPolicy.REPORT_CLUSTER_EVENTS)
787             System.err.println("cluster=" + clusterUID + " id=" + clusterId + " key=" + clusterKey + " resources will be updated.");
788         // get cluster change sets
789         QueryProcessor queryProcessor = session.getQueryProvider2();
790         ClusterChanges cc;
791         try {
792             cc = session.graphSession.getClusterChanges(clusterUID, csid);
793         } catch (Exception e) {
794             Logger.defaultLogError("Could not get cluster changes. cluster=" + clusterUID, e);
795             release(clusterId);
796             return;
797         }
798         for (int i=0; i<cc.getResourceIndex().length; ++i) {
799             int resource = ClusterTraits.createResourceKey(clusterKey, cc.getResourceIndex()[i]);
800             ClusterUID pClusterUID = new ClusterUID(cc.getPredicateFirst()[i], cc.getPredicateSecond()[i]);
801             ClusterImpl pCluster = clusters.getClusterByClusterUID(pClusterUID);
802             if (null == pCluster)
803                 continue;
804             int pClusterKey = pCluster.getClusterKey();
805             int predicate = ClusterTraits.createResourceKey(pClusterKey, cc.getPredicateIndex()[i]);
806             queryProcessor.updateStatements(resource, predicate);
807             if (DebugPolicy.REPORT_CLUSTER_EVENTS)
808                 System.err.println("resource " + cc.getResourceIndex()[i] + " relation " + cc.getPredicateIndex()[i] + " changed.");
809         }
810         for (int i=0; i<cc.getValueIndex().length; ++i) {
811             int resource = ClusterTraits.createResourceKey(clusterKey, cc.getValueIndex()[i]);
812             queryProcessor.updateValue(resource);
813             if (DebugPolicy.REPORT_CLUSTER_EVENTS)
814                 System.err.println("value " + cc.getValueIndex()[i] + " changed.");
815         }
816     }
817     final void refreshImportance(ClusterImpl c) {
818
819         if (c.isWriteOnly())
820             return;
821
822         //printMaps("refreshImportance");
823
824         importanceMap.remove(c.getImportance());
825         if(collectorPolicy != null) collectorPolicy.removed(c);
826
827         long newImportance = timeCounter();
828 // System.err.println("refreshImportance " + c.getClusterId() + " => " + newImportance);
829         c.setImportance(newImportance);
830         if (!c.isLoaded())
831             Logger.defaultLogError(new Exception("Bug in ClusterTable.refreshImportance(ClusterImpl), cluster not loaded"));
832
833         importanceMap.put(c.getImportance(), new ImportanceEntry(c));
834         if(collectorPolicy != null) collectorPolicy.added(c);
835         if (VALIDATE_SIZE)
836             validateSize("refreshImportance");
837
838     }
839
840     static long loadTime = 0;
841
842     @SuppressWarnings("unchecked")
843     public final <T extends ClusterI> T getClusterProxyByResourceKey(final int resourceKey) {
844         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
845         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
846             throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
847         ClusterI cluster = clusterArray[clusterKey];
848         if (cluster == null)
849             throw new RuntimeException("No proxy for existing cluster. Resource key = " + resourceKey);
850         return (T)cluster;
851     }
852
853     TLongIntHashMap clusterLoadHistogram = new TLongIntHashMap();
854     int clusterLoadCounter = 0;
855
856     private <T extends ClusterI> T ensureLoaded(T c) {
857         ClusterI cluster;
858         ClusterImpl cs = (ClusterImpl) c;
859         try {
860             if(DebugPolicy.REPORT_CLUSTER_LOADING) {
861                 long start = System.nanoTime();
862                 cluster = load2(cs.getClusterId(), cs.getClusterKey());
863                 long load = System.nanoTime()-start;
864                 loadTime +=  load;
865                 if(DebugPolicy.REPORT_CLUSTER_LOADING) {
866                     int was = clusterLoadHistogram.get(cluster.getClusterId());
867                     clusterLoadHistogram.put(cluster.getClusterId(), was+1);
868                     clusterLoadCounter++;
869                     String text = "Load2 " + cluster + " " + 1e-9*loadTime + "s. " + 1e-6*load + "ms. " + clusterLoadCounter + " " + was + " " + cluster.getUsedSpace() + " " + cluster.getImportance();
870                     if(DebugPolicy.REPORT_CLUSTER_LOADING_STACKS) {
871                         new Exception(text).printStackTrace();
872                     } else {
873                         System.err.println(text);
874                     }
875                 }
876             } else {
877                 cluster = load2(cs.getClusterId(), cs.getClusterKey());
878             }
879         } catch (DatabaseException e) {
880             Logger.defaultLogError(e);
881             if (DebugPolicy.REPORT_CLUSTER_EVENTS)
882                 e.printStackTrace();
883             String msg = "Failed to load cluster " + cs.getClusterUID();// + " resourceId=" + (((cs.getClusterId() << 16 + (resourceKey & 65535))));
884             // TODO: this jams the system => needs refactoring.
885             throw new RuntimeDatabaseException(msg, e);
886         }
887         return (T) cluster;
888     }
889     
890     @SuppressWarnings("unchecked")
891     public final <T extends ClusterI> T getClusterByResourceKey(final int resourceKey) {
892         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
893         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
894             throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
895         ClusterI c = clusterArray[clusterKey];
896         if (c == null)
897             return null;
898         if (c.isLoaded()) {
899             if ((counter++ & 4095) == 0)
900                 refreshImportance((ClusterImpl) c);
901             return (T) c;
902         }
903         if (!(c instanceof ClusterSmall)) {
904             Logger.defaultLogError("Proxy must be instance of ClusterSmall");
905             return null;
906         }
907         return ensureLoaded((T)c);
908     }
909
910     @SuppressWarnings("unchecked")
911     final <T extends ClusterI> T checkedGetClusterByResourceKey(final int resourceKey) {
912         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
913         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
914             throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
915         ClusterI c = clusterArray[clusterKey];
916         if (c == null)
917             throw new RuntimeException("No cluster for resource key " + resourceKey);
918         if (c.isLoaded()) {
919             if ((counter++ & 4095) == 0)
920                 refreshImportance((ClusterImpl) c);
921             return (T) c;
922         }
923         if (!(c instanceof ClusterSmall)) {
924             Logger.defaultLogError("Proxy must be instance of ClusterSmall");
925             return null;
926         }
927         ClusterI cluster;
928         ClusterSmall cs = (ClusterSmall) c;
929         try {
930 //          System.err.println("Load2 " + resourceKey);
931             cluster = load2(cs.getClusterId(), cs.getClusterKey());
932         } catch (DatabaseException e) {
933             if (DebugPolicy.REPORT_CLUSTER_EVENTS)
934                 e.printStackTrace();
935             int resourceIndex = resourceKey & ClusterTraitsBase.getResourceIndexFromResourceKeyNoThrow(resourceKey);
936             long resourceId = ClusterTraitsBase.createResourceIdNoThrow(cs.getClusterId(), resourceIndex);
937             String msg = "Failed to load cluster " + cs.getClusterUID() + " for resource key " + resourceKey + " resourceIndex=" + resourceIndex + " resourceId=" + resourceId;
938             Logger.defaultLogError(msg, e);
939             c.setDeleted(true, null);
940             return (T)c;
941         }
942         return (T) cluster;
943     }
944
945     void printDebugInfo(ClusterSupport support)
946             throws DatabaseException {
947         final int SIZE = clusters.size();
948         long sum = 0;
949         for (int i = 1; i < SIZE; ++i) {
950             ClusterI c = clusterArray[i];
951             c.getNumberOfResources(support);
952             long size = c.getUsedSpace();
953             System.out.println("cluster=" + c.getClusterId() + " size=" + size);
954             c.printDebugInfo("koss: ", support);
955             sum += size;
956         }
957         System.out.println("Total number of clusters " + SIZE);
958         System.out.println("Total cluster size " + sum);
959     }
960
961     Map<Long,ClusterImpl> prefetch = new HashMap<Long,ClusterImpl>();
962
963     public synchronized ClusterImpl load2(long clusterId, int clusterKey) throws DatabaseException {
964         ClusterImpl curr = (ClusterImpl) clusterArray[clusterKey];
965         if (curr.isLoaded())
966             return curr;
967
968 //        getPrefetched();
969 //
970 //        curr = (ClusterImpl) clusterArray[clusterKey];
971 //        if (curr.isLoaded())
972 //            return curr;
973
974         final Semaphore s = new Semaphore(0);
975         final DatabaseException[] ex = new DatabaseException[1];
976
977         load2(clusterId, clusterKey, e -> {
978             ex[0] = e;
979             s.release();
980         });
981         try {
982             s.acquire();
983         } catch (InterruptedException e) {
984             Logger.defaultLogError(e);
985         }
986         if (null != ex[0])
987             throw ex[0];
988         if (Development.DEVELOPMENT) {
989             if (Development.<Boolean>getProperty(DevelopmentKeys.CLUSTERTABLE_VALIDATE_ON_LOAD, Bindings.BOOLEAN)) {
990                 try {
991                     ClusterImpl loaded = (ClusterImpl) clusterArray[clusterKey];
992                     if (loaded instanceof ClusterSmall)
993                         ((ClusterSmall) loaded).check();
994                     else if (loaded instanceof ClusterBig)
995                         ((ClusterBig) loaded).check();
996                 } catch (Throwable t) {
997                     t.printStackTrace();
998                 }
999             }
1000         }
1001         
1002         validate(clusterKey);
1003         
1004         return (ClusterImpl) clusterArray[clusterKey];
1005     }
1006     
1007     void validate(int clusterKey) {
1008         
1009 //      if(sessionImpl.graphSession.graphClient instanceof GraphClientImpl2) {
1010 //          
1011 //        ClusterImpl server = (ClusterImpl)clusterArray[clusterKey]; 
1012 //        String sd = server.dump(sessionImpl.clusterTranslator);
1013 //        GraphClientImpl2 gci = ((GraphClientImpl2)sessionImpl.graphSession.graphClient);
1014 //        ClusterImpl memory = gci.clusters.get(server.clusterUID);
1015 //        if(memory == null)
1016 //            System.err.println("ad");
1017 //        String md = memory.dump(gci.support);
1018 //        
1019 //        if(!sd.equals(md)) {
1020 //            
1021 //            int diffPos = 0;
1022 //            int minLength = Math.min(sd.length(), md.length());
1023 //            for (int i = 0; i < minLength; i++) {
1024 //                if (sd.charAt(i) != md.charAt(i)) {
1025 //                    diffPos = i;
1026 //                    break;
1027 //                }
1028 //            }
1029 //            
1030 //            int start = Math.max(diffPos-200, 0);
1031 //            int end = Math.min(minLength-1, diffPos+200);
1032 //
1033 //            System.err.println("== CLUSTER DIFFERENCE " + clusterArray[clusterKey].getClusterUID() +  " == ");
1034 //            System.err.println("== SESSION == ");
1035 //            System.err.println(sd.substring(start, end));
1036 //            System.err.println("== MEM == ");
1037 //            System.err.println(md.substring(start, end));
1038 //            System.err.println("== CLUSTER DIFFERENCE ENDS == ");
1039 //            
1040 //            throw new IllegalStateException();
1041 //        }
1042 //        
1043 //      }
1044     }
1045
1046     public synchronized ClusterImpl getPrefetched() {
1047         synchronized(prefetch) {
1048             return null;
1049         }
1050     }
1051
1052     public synchronized void load2(long clusterId, int clusterKey, final Consumer<DatabaseException> runnable) {
1053
1054         assert (Constants.ReservedClusterId != clusterId);
1055
1056         ClusterImpl cluster = null;
1057         DatabaseException e = null;
1058
1059         try {
1060
1061             ClusterUID clusterUID = clusters.makeClusterUID(clusterId);
1062 //            cluster = (ClusterImpl) sessionImpl.getGraphSession().getClusterImpl(clusterUID, clusterKey);
1063             Database.Session session = sessionImpl.graphSession.dbSession;
1064 //            cluster = (ClusterImpl)gci.getClusterByClusterKey(clusterKey).clone(sessionImpl.clusterTranslator);
1065 //            cluster = (ClusterImpl)((ClusterImpl)gci.getClusterByClusterUIDOrMakeProxy(clusterUID)).clone(sessionImpl.clusterTranslator);
1066             
1067 //            cluster = gci.clone(clusterUID, sessionImpl.clusterTranslator);
1068             
1069             cluster = session.clone(clusterUID, new ClusterCreator() {
1070                 
1071                 @Override
1072                 public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
1073                     ClusterSupport support = sessionImpl.clusterTranslator;
1074                     try {
1075                         return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
1076                     } catch (DatabaseException e) {
1077                         e.printStackTrace();
1078                         return null;
1079                     }
1080                 }
1081                 
1082             });
1083             
1084         } catch (Throwable t) {
1085             // It's totally legal to call for non-existing cluster.
1086             // Sometimes this indicates an error, though.
1087             Logger.getDefault().logInfo("Load cluster failed.", t);
1088             if (t instanceof DatabaseException)
1089                 e = (DatabaseException) t;
1090             else
1091                 e = new DatabaseException("Load cluster failed.", t);
1092         }
1093         if (null == cluster) {
1094             runnable.accept(e);
1095             return;
1096         }
1097
1098 //      new Exception("Load cluster " + cluster.getClusterId() + " " + cluster.getCachedSize() + " " + cluster.getImmutable()).printStackTrace();
1099
1100         // Can not be called with null argument.
1101         replaceCluster(cluster);
1102         sessionImpl.onClusterLoaded(clusterId);
1103         runnable.accept(null);
1104
1105     }
1106
1107     public synchronized ClusterImpl tryLoad(long clusterId, int clusterKey) throws DatabaseException {
1108
1109         assert (Constants.ReservedClusterId != clusterId);
1110
1111         ClusterUID clusterUID = clusters.makeClusterUID(clusterId);
1112         
1113         Database.Session session = sessionImpl.graphSession.dbSession;
1114         
1115         ClusterImpl cluster = session.clone(clusterUID, new ClusterCreator() {
1116             
1117             @Override
1118             public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
1119                 ClusterSupport support = sessionImpl.clusterTranslator;
1120                 try {
1121                     return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
1122                 } catch (DatabaseException e) {
1123                     e.printStackTrace();
1124                     return null;
1125                 }
1126             }
1127             
1128         });
1129         if (null == clusterArray[clusterKey])
1130             clusterArray[clusterKey] = cluster;
1131         else
1132             replaceCluster(cluster);
1133         sessionImpl.onClusterLoaded(clusterId);
1134         
1135         validate(clusterKey);
1136         
1137         return cluster;
1138     }
1139
1140     public Collection<ClusterI> getClusters() {
1141         ArrayList<ClusterI> result = new ArrayList<ClusterI>();
1142         for (int i = 0; i < clusterArray.length; i++) {
1143             ClusterI cluster = clusterArray[i];
1144             if (cluster != null)
1145                 result.add(cluster);
1146         }
1147         return result;
1148     }
1149
1150     public int size() {
1151         return clusters.size();
1152     }
1153
1154     public long timeCounter() {
1155         return timeCounter.getAndIncrement();
1156     }
1157
1158     public boolean hasVirtual(int index) {
1159         return virtuals[index];
1160     }
1161
1162     public void markVirtual(int index) {
1163         virtuals[index] = true;
1164     }
1165
1166     public ClusterImpl[] getClusterArray() {
1167         return clusterArray;
1168     }
1169
1170     public boolean isImmutable(int id) {
1171
1172         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(id);
1173         Boolean exist = immutables[clusterKey];
1174         if(exist != null) return exist;
1175
1176         ClusterI cluster = getClusterByResourceKey(id);
1177         if(cluster == null) {
1178                 return false;
1179         } else {
1180                 boolean result = cluster.getImmutable();
1181                 markImmutable(cluster, result);
1182                 return result;
1183         }
1184         
1185     }
1186
1187     public void markImmutable(ClusterI cluster, boolean value) {
1188         immutables[cluster.getClusterKey()] = value;
1189     }
1190     @Override
1191     public int getClusterKeyByUID(long first, long second) throws DatabaseException {
1192         return getClusterKeyByClusterUIDOrMakeProxy(ClusterUID.make(first, second));
1193     }
1194
1195     public void adjustCachedSize(long l, ClusterI cluster) {
1196         if (l != 0) {
1197             //System.out.println("ClusterTable: adjusting cluster table cached size by " + l + ": " + sizeInBytes + " -> "
1198             //        + (sizeInBytes + l) + ", for cluster " + cluster.getClusterId() + " (" + cluster + ")");
1199             sizeInBytes += l;
1200         }
1201     }
1202
1203     private void validateSize(String place) {
1204         if (!VALIDATE_SIZE)
1205             return;
1206
1207         int ims = importanceMap.size();
1208         int ihms = countImportantClusters();
1209
1210 //        System.out.format("[%s] Validating ClusterTable: byteSize=%d, hashMap=%d/%d, importanceMap=%d%n",
1211 //                place, sizeInBytes, ihms, clusters.hashMap.size(), ims);
1212
1213         int i = clusterArray.length;
1214         long size = 0;
1215         for (int j = 0; j < i; ++j) {
1216             ClusterI c = clusterArray[j];
1217             if (c == null)
1218                 continue;
1219             size += c.getCachedSize();
1220         }
1221         if (sizeInBytes != size) {
1222             if (!dirtySizeInBytes)
1223                 System.out.println("BUG: CACHED CLUSTER SIZE DIFFERS FROM CALCULATED: " + sizeInBytes + " != " + size + ", delta = " + (sizeInBytes - size));
1224             //else System.out.println("\"BUG?\": SIZES DIFFER: " + sizeInBytes + " != " + size + ", delta = " + (sizeInBytes - size));
1225         }
1226         if (ims != ihms) {
1227             System.out.println("BUG2: hashmap and importanceMap sizes differ: " + ihms + " != " + ims + ", delta=" + (ihms - ims));
1228             printMaps("validateSize");
1229         }
1230         //System.out.println("[" + place + "] VALIDATED");
1231     }
1232
1233     private void printMaps(String place) {
1234         int ihms = countImportantClusters();
1235         System.out.println("## printMaps(" + place + ") - " + importanceMap.size() + " - (" + ihms + "/" + clusters.hashMap.size() + ")");
1236         System.out.println("importanceMap (" + importanceMap.size() + "):");
1237         importanceMap.forEach((importance, ie) -> {
1238             System.out.format("\t%d: %s%n", importance, ie.toString());
1239         });
1240         System.out.println("clusters.hashMap (" + ihms + "/" + clusters.hashMap.size() + "):");
1241         clusters.hashMap.forEachEntry((cid, c) -> {
1242             boolean important = importantCluster(c);
1243             boolean wo = c != null && c.isWriteOnly();
1244             boolean empty = c != null && c.isEmpty();
1245             boolean loaded = c != null && c.isLoaded();
1246             System.out.format("\t%s: %d - %s (writeOnly=%b, empty=%b, loaded=%b)%n", important ? " I" : "NI", cid, c, wo, empty, loaded);
1247             return true;
1248         });
1249     }
1250
1251     private int countImportantClusters() {
1252         int[] result = { 0 };
1253         clusters.hashMap.forEachEntry((cid, c) -> {
1254             if (importantCluster(c))
1255                 result[0]++;
1256             return true;
1257         });
1258         return result[0];
1259     }
1260
1261     private static boolean importantCluster(ClusterImpl c) {
1262         return c != null && !c.isWriteOnly() && c.isLoaded();// && !c.isEmpty();
1263     }
1264
1265 }