]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.procore/src/fi/vtt/simantics/procore/internal/ClusterTable.java
Better fix for ClusterTable maps going out of sync
[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         importanceMap.remove(existing.getImportance());
301         if (collectorPolicy != null)
302             collectorPolicy.removed((ClusterImpl)existing);
303
304         //System.out.println("ClusterTable.replace(" + existing + " (I=" + existing.getImportance() + ") => " + cluster + " (I=" + cluster.getImportance() + ")");
305
306         clusters.replace((ClusterImpl)cluster);
307         if (!cluster.isLoaded())
308             Logger.defaultLogError(new Exception("Bug in ClusterTable.replaceCluster(ClusterI), cluster not loaded"));
309
310         importanceMap.put(cluster.getImportance(), new ImportanceEntry((ClusterImpl)cluster));
311         if(collectorPolicy != null) collectorPolicy.added((ClusterImpl)cluster);
312
313         if (!dirtySizeInBytes) {
314             if (existing != cluster) {
315                 adjustCachedSize(-existing.getCachedSize(), existing);
316             }
317             // This will update sizeInBytes through adjustCachedSize
318             cluster.getCachedSize();
319         }
320         if (VALIDATE_SIZE)
321             validateSize("replaceCluster");
322     }
323
324     synchronized void release(CollectorCluster cluster) {
325         importanceMap.remove(cluster.getImportance());
326         release(cluster.getClusterId());
327     }
328
329     synchronized void release(long clusterId) {
330         //System.out.println("ClusterTable.release(" + clusterId + "): " + sizeInBytes);
331         //validateSize();
332         ClusterImpl clusterImpl = clusters.getClusterByClusterId(clusterId);
333         if (null == clusterImpl)
334             return;
335         if(!clusterImpl.isLoaded() || clusterImpl.isEmpty())
336             return;
337         //printMaps("release");
338         clusters.freeProxy(clusterImpl);
339         importanceMap.remove(clusterImpl.getImportance());
340         if (collectorPolicy != null)
341             collectorPolicy.removed(clusterImpl);
342         if (sessionImpl.writeState != null)
343             sessionImpl.clusterStream.flush(clusterImpl.clusterUID);
344         if (!dirtySizeInBytes) {
345             adjustCachedSize(-clusterImpl.getCachedSize(), clusterImpl);
346         }
347         if (VALIDATE_SIZE)
348             validateSize("release");
349     }
350
351     synchronized void compact(long id) {
352         ClusterI impl = clusters.getClusterByClusterId(id);
353         if (impl != null)
354             impl.compact();
355     }
356
357     void updateSize() {
358 // cachedSize = getSizeInBytes();
359     }
360
361     double getLoadProbability() {
362         // This can currently cause stack overflow
363         return 1.0;
364 // if(cachedSize < SLOW_LIMIT) return 1.0;
365 // if(cachedSize > HIGH_LIMIT) return 1e-2;
366 //
367 // double pos = (double)(cachedSize - SLOW_LIMIT) / (double)(HIGH_LIMIT -
368 // SLOW_LIMIT);
369 // double val = 0.1 * ((pos-1) * (pos-1)) + 1e-2;
370 // return val;
371     }
372
373     class SizeProcedure implements TObjectProcedure<ClusterImpl> {
374         public long result = 0;
375
376         @Override
377         public boolean execute(ClusterImpl cluster) {
378             if (cluster != null) {
379                 try {
380                     if (cluster.isLoaded() && !cluster.isEmpty()) {
381                         result += cluster.getCachedSize();
382                     }
383                 } catch (Throwable t) {
384                     Logger.defaultLogError(t);
385                 }
386             }
387             return true;
388         }
389
390         public void clear() {
391             result = 0;
392         }
393
394     };
395
396     private SizeProcedure sizeProcedure = new SizeProcedure();
397     long getSizeInBytes() {
398         if (dirtySizeInBytes) {
399             sizeProcedure.clear();
400             clusters.forEachValue(sizeProcedure);
401             sizeInBytes = sizeProcedure.result;
402             // System.err.println("recomputed size of clusterTable => " + sizeInBytes);
403             setDirtySizeInBytes(false);
404         }
405         return sizeInBytes;
406     }
407
408     public void setDirtySizeInBytes(boolean value) {
409         dirtySizeInBytes = value;
410     }
411
412     ClusterStateImpl getState() {
413         final ClusterStateImpl result = new ClusterStateImpl();
414         clusters.forEachEntry(new TLongObjectProcedure<ClusterImpl>() {
415             @Override
416             public boolean execute(long arg0, ClusterImpl arg1) {
417                 if (arg1 == null)
418                     return true;
419                 if (arg1.isLoaded() && !arg1.isEmpty()) {
420                     result.ids.add(new ImportanceEntry(arg1));
421                 }
422                 return true;
423             }
424         });
425         return result;
426     }
427
428     void restoreState(ClusterStateImpl state) {
429         ClusterStateImpl current = getState();
430         for (CollectorCluster id : current.ids)
431             if (!state.ids.contains(id))
432                 collectorSupport.release(id);
433     }
434
435     class ClusterCollectorImpl implements ClusterCollector {
436
437         final private ClusterCollectorSupport support;
438         private ClusterCollectorPolicy policy;
439         ClusterCollectorImpl(ClusterCollectorSupport support) {
440             this.support = support;
441         }
442
443         ClusterCollectorPolicy setPolicy(ClusterCollectorPolicy newPolicy) {
444
445             ClusterCollectorPolicy oldPolicy = policy;
446             policy = newPolicy;
447
448             if(policy != null) {
449                 for (CollectorCluster id : support.getResidentClusters()) {
450                     policy.added(getClusterByClusterId(id.getClusterId()));
451                 }
452             }
453
454             support.setPolicy(policy);
455
456             return oldPolicy;
457
458         }
459
460         @Override
461         public void collect() {
462
463             if(policy != null) {
464
465                 release(policy.select());
466
467             } else {
468
469                 int size = support.getCurrentSize();
470                 boolean dynamicAllocation = useDynamicAllocation();
471                 if (dynamicAllocation)
472                     setAllocateSize(estimateProperAllocation(support));
473                 if (DebugPolicy.CLUSTER_COLLECTION) {
474                     System.out.println("Cluster collector activated, current size = " + size + " limit = " + maximumBytes);
475                 }
476                 if (dynamicAllocation) {
477                     int collectSize = maximumBytes / 2;
478                     collectSize = Math.min(collectSize, 32 * 1024 * 1024);
479                     // try to keep allocated clusters below the maximum
480                     if (maximumBytes - size > collectSize)
481                         return;
482                     collectSize += size - maximumBytes;
483                     collect(collectSize);
484                 } else {
485                     // try to keep allocated clusters below the maximum
486                     if (size < maximumBytes)
487                         return;
488                     // shave off 20%
489                     collect(size-limit);
490                 }
491
492             }
493
494         }
495
496         private boolean useDynamicAllocation() {
497             return "true".equalsIgnoreCase(System.getProperty("org.simantics.db.cluster.dynamicAlloc"));
498         }
499
500         @Override
501         public void collect(int target) {
502
503             if(policy != null) {
504
505                 release(policy.select(target));
506
507             } else {
508
509                 ArrayList<CollectorCluster> toRelease = new ArrayList<CollectorCluster>();
510
511                 for (CollectorCluster cluster : support.getResidentClusters()) {
512                     target -= support.getClusterSize(cluster);
513                     if (target > 0) {
514                         toRelease.add(cluster);
515                     } else {
516                         break;
517                     }
518                 }
519
520                 release(toRelease);
521
522                 if (DebugPolicy.CLUSTER_COLLECTION) {
523                     System.out.println("Cluster collector finished, current size = " + support.getCurrentSize());
524                 }
525
526             }
527
528         }
529
530         void release(Collection<CollectorCluster> toRelease) {
531             for (CollectorCluster id : toRelease) {
532                 support.release(id);
533             }
534         }
535
536     }
537
538     private ClusterCollectorSupport collectorSupport = new ClusterCollectorSupportImpl(this);
539     ClusterCollectorImpl collector = new ClusterCollectorImpl(collectorSupport);
540
541     void gc() {
542         collector.collect();
543     }
544
545     private long newResourceClusterId = Constants.NewClusterId;
546     public static final int CLUSTER_FILL_SIZE = ClusterTraitsBase.getMaxNumberOfResources();
547
548     /*
549      * Uusi id varataan vasta, kun lis�t��n resurssi => reservedIds sis�lt��
550      * vain jo k�yt�ss� olevia klustereita
551      */
552
553     ClusterImpl getNewResourceCluster(ClusterSupport cs, GraphSession graphSession, boolean writeOnly)
554     throws DatabaseException {
555         ClusterImpl result = null;
556         if (Constants.NewClusterId == newResourceClusterId) {
557             newResourceClusterId = graphSession.newClusterId();
558             result = getClusterByClusterIdOrMake(newResourceClusterId, writeOnly);
559         } else {
560             ClusterImpl cluster = getClusterByClusterIdOrThrow(newResourceClusterId);
561             if (cluster.getNumberOfResources(cs) >= CLUSTER_FILL_SIZE) {
562                 newResourceClusterId = graphSession.newClusterId();
563                 cluster = getClusterByClusterIdOrMake(newResourceClusterId, writeOnly);
564             }
565             result = cluster;
566         }
567         return ensureLoaded(result);
568     }
569
570     void flushCluster(GraphSession graphSession) {
571 // We seem to disagree about this.
572 // graphSession.newClusterId();
573         newResourceClusterId = Constants.NewClusterId;
574     }
575
576     void writeOnlyInvalidate(ClusterI impl) {
577         writeOnlyInvalidates.add(impl.getClusterKey());
578     }
579
580     void removeWriteOnlyClusters() {
581         for (ClusterI proxy : writeOnlyClusters) {
582             if (!(proxy instanceof ClusterImpl))
583                 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
584             clusters.freeProxy((ClusterImpl)proxy);
585         }
586         writeOnlyClusters.clear();
587         writeOnlyInvalidates.forEach(new TIntProcedure() {
588             @Override
589             public boolean execute(int clusterKey) {
590                 ClusterImpl proxy = clusterArray[clusterKey];
591                 ClusterUID clusterUID = proxy.getClusterUID();
592                 System.err.println("writeOnlyInvalidate " + clusterUID);
593                 clusters.freeProxy(proxy);
594                 return true;
595             }
596         });
597         writeOnlyInvalidates.clear();
598     }
599
600     public ClusterImpl getClusterByClusterUID(ClusterUID clusterUID) {
601         synchronized (this) {
602             return clusters.getClusterByClusterUID(clusterUID);
603         }
604     }
605     public int getClusterKeyByClusterUIDOrMakeProxy(ClusterUID clusterUID) {
606         return getClusterKeyByClusterUIDOrMakeProxy(0/*clusterUID.first*/, clusterUID.second);
607     }
608     public int getClusterKeyByClusterUIDOrMakeProxy(long id1, long id2) {
609         return getClusterByClusterUIDOrMakeProxy(id1, id2).clusterKey;
610     }
611     public ClusterImpl getClusterByClusterUIDOrMakeProxy(ClusterUID clusterUID) {
612         synchronized (this) {
613             ClusterImpl clusterImpl = clusters.getClusterByClusterUID(clusterUID);
614             if (null == clusterImpl)
615                 clusterImpl = clusters.makeProxy(clusterUID);
616             return clusterImpl;
617         }
618     }
619     public ClusterImpl getClusterByClusterUIDOrMakeProxy(long id1, long id2) {
620         synchronized (this) {
621             ClusterImpl clusterImpl = clusters.getClusterByClusterUID(id1, id2);
622             if (null == clusterImpl)
623                 clusterImpl = clusters.makeProxy(id2);
624             return clusterImpl;
625         }
626     }
627     ClusterImpl getLoadOrThrow(long clusterId) throws DatabaseException {
628         synchronized (this) {
629             ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
630             int clusterKey = 0;
631             if (proxy != null)
632                 if (proxy.isLoaded())
633                     return proxy;
634                 else
635                     clusterKey = proxy.getClusterKey();
636             try {
637                 if (clusterKey == 0) {
638                     proxy = clusters.makeProxy(clusterId);
639                     clusterKey = proxy.getClusterKey();
640                 }
641                 ClusterImpl ci = tryLoad(clusterId, clusterKey);
642                 if (null == ci)
643                     throw new ResourceNotFoundException(clusterId);
644                 return ci;
645             } catch (ClusterDoesNotExistException t) {
646                 clusters.removeProxy(proxy);
647                 throw t;
648             }
649         }
650     }
651
652     ClusterImpl getClusterByClusterIdOrMake(long clusterId, boolean writeOnly) {
653         synchronized (this) {
654             ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
655             if (proxy != null)
656                 return proxy;
657             else
658                 return makeCluster(clusterId, writeOnly);
659         }
660     }
661     ClusterImpl getClusterByClusterIdOrThrow(long clusterId) {
662         synchronized (this) {
663             ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
664             if (null == proxy)
665                 throw new IllegalArgumentException("Cluster id=" + clusterId + " is not created.");
666             return proxy;
667         }
668     }
669     long getClusterIdOrCreate(ClusterUID clusterUID) {
670         return clusterUID.second;
671     }
672     final long getClusterIdByResourceKey(final int resourceKey)
673     throws DatabaseException {
674         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKey(resourceKey);
675         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
676             throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
677         ClusterI c = clusterArray[clusterKey];
678         if (c == null)
679             throw new RuntimeException("No cluster for key " + resourceKey);
680         return c.getClusterId();
681     }
682     final long getClusterIdByResourceKeyNoThrow(final int resourceKey) {
683         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
684         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey)) {
685             Logger.defaultLogError("Tried to get a persistent cluster for a virtual resource. key=" + resourceKey);
686             return 0;
687         }
688         ClusterI c = clusterArray[clusterKey];
689         if (c == null) {
690             Logger.defaultLogError("No cluster for key " + resourceKey);
691             return 0;
692         }
693         return c.getClusterId();
694     }
695
696     int counter = 0;
697
698     void refresh(long csid, SessionImplSocket session, ClusterUID[] clusterUID) {
699         synchronized (this) {
700             session.flushCounter = 0;
701             session.clusterStream.reallyFlush();
702             ClientChangesImpl cs = new ClientChangesImpl(session);
703             if (session.clientChanges == null)
704                 session.clientChanges = cs;
705             //printMaps("refresh");
706             for (int i=0; i<clusterUID.length; ++i) {
707                 try {
708                     if (DebugPolicy.REPORT_CLUSTER_EVENTS)
709                         System.err.println("cluster=" + clusterUID[i] + " has changed. length=" + clusterUID.length);
710                     ClusterImpl oldCluster = clusters.getClusterByClusterUID(clusterUID[i]);
711                     if (null == oldCluster)
712                         continue;
713                     if (!oldCluster.isLoaded())
714                         continue;
715                     int clusterKey = oldCluster.getClusterKey();
716                     if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
717                         continue;
718                     boolean big = oldCluster instanceof ClusterBig;
719                     boolean small = oldCluster instanceof ClusterSmall;
720                     if (!big && !small)
721                         continue;
722 //                    ClusterImpl newCluster = (ClusterImpl) sessionImpl.graphSession.getClusterImpl(clusterUID[i], clusterKey);
723                     Database.Session dbSession = sessionImpl.graphSession.dbSession;
724                     
725                     ClusterImpl newCluster = dbSession.clone(clusterUID[i], new ClusterCreator() {
726                         
727                         @Override
728                         public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
729                             ClusterSupport support = sessionImpl.clusterTranslator;
730                             try {
731                                 return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
732                             } catch (DatabaseException e) {
733                                 e.printStackTrace();
734                                 return null;
735                             }
736                         }
737                         
738                     });
739                     if (null == newCluster)
740                         continue;
741                     if (DebugPolicy.REPORT_CLUSTER_EVENTS)
742                         System.err.println("cluster=" + newCluster + "  updated.");
743                     importanceMap.remove(oldCluster.getImportance());
744                     if (collectorPolicy != null)
745                         collectorPolicy.removed(oldCluster);
746                     clusters.replace(newCluster);
747                     if (!newCluster.isLoaded())
748                         Logger.defaultLogError(new Exception("Bug in ClusterTable.refresh, cluster not loaded"));
749                     importanceMap.put(newCluster.getImportance(), new ImportanceEntry(newCluster));
750                     if (collectorPolicy != null)
751                         collectorPolicy.added(newCluster);
752                     // Now we have fetched the new cluster but to emulate effects of the changes in it we fetch the cluster changes from server.
753                     refreshCluster(csid, session, oldCluster, clusterUID[i], newCluster.clusterId, clusterKey);
754                 } catch (Throwable t) {
755                     Logger.defaultLogError("Failed to load cluster in refresh.", t);
756                 }
757             }
758             if (VALIDATE_SIZE)
759                 validateSize("refresh");
760             // Fake update of cluster changes.
761             QueryProcessor queryProcessor = session.getQueryProvider2();
762             WriteGraphImpl writer = WriteGraphImpl.create(queryProcessor, session.writeSupport, null);
763             TaskHelper th = null;
764             if (null == session.writeState) {
765                 th = new TaskHelper("Refresh");
766                 session.writeState = new WriteState<Object>(writer, th.writeTraits, th.sema, th.proc);
767                 try {
768                     session.getQueryProvider2().performDirtyUpdates(writer);
769                     session.fireMetadataListeners(writer, cs);
770                     session.getQueryProvider2().performScheduledUpdates(writer);
771                     session.fireReactionsToSynchronize(cs);
772                     session.fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
773                     session.printDiagnostics();
774                 } finally {
775                     if (null != th)
776                         session.writeState = null;
777                     cs.dispose();
778                 }
779             }
780         }
781     }
782     final void refreshCluster(long csid, SessionImplSocket session, ClusterImpl cluster, ClusterUID clusterUID, long clusterId, int clusterKey)
783     throws DatabaseException {
784         if (DebugPolicy.REPORT_CLUSTER_EVENTS)
785             System.err.println("cluster=" + clusterUID + " id=" + clusterId + " key=" + clusterKey + " resources will be updated.");
786         // get cluster change sets
787         QueryProcessor queryProcessor = session.getQueryProvider2();
788         ClusterChanges cc;
789         try {
790             cc = session.graphSession.getClusterChanges(clusterUID, csid);
791         } catch (Exception e) {
792             Logger.defaultLogError("Could not get cluster changes. cluster=" + clusterUID, e);
793             release(clusterId);
794             return;
795         }
796         for (int i=0; i<cc.getResourceIndex().length; ++i) {
797             int resource = ClusterTraits.createResourceKey(clusterKey, cc.getResourceIndex()[i]);
798             ClusterUID pClusterUID = new ClusterUID(cc.getPredicateFirst()[i], cc.getPredicateSecond()[i]);
799             ClusterImpl pCluster = clusters.getClusterByClusterUID(pClusterUID);
800             if (null == pCluster)
801                 continue;
802             int pClusterKey = pCluster.getClusterKey();
803             int predicate = ClusterTraits.createResourceKey(pClusterKey, cc.getPredicateIndex()[i]);
804             queryProcessor.updateStatements(resource, predicate);
805             if (DebugPolicy.REPORT_CLUSTER_EVENTS)
806                 System.err.println("resource " + cc.getResourceIndex()[i] + " relation " + cc.getPredicateIndex()[i] + " changed.");
807         }
808         for (int i=0; i<cc.getValueIndex().length; ++i) {
809             int resource = ClusterTraits.createResourceKey(clusterKey, cc.getValueIndex()[i]);
810             queryProcessor.updateValue(resource);
811             if (DebugPolicy.REPORT_CLUSTER_EVENTS)
812                 System.err.println("value " + cc.getValueIndex()[i] + " changed.");
813         }
814     }
815     final void refreshImportance(ClusterImpl c) {
816
817         if (c.isWriteOnly())
818             return;
819
820         //printMaps("refreshImportance");
821
822         importanceMap.remove(c.getImportance());
823         if(collectorPolicy != null) collectorPolicy.removed(c);
824
825         long newImportance = timeCounter();
826 // System.err.println("refreshImportance " + c.getClusterId() + " => " + newImportance);
827         c.setImportance(newImportance);
828         if (!c.isLoaded())
829             Logger.defaultLogError(new Exception("Bug in ClusterTable.refreshImportance(ClusterImpl), cluster not loaded"));
830
831         importanceMap.put(c.getImportance(), new ImportanceEntry(c));
832         if(collectorPolicy != null) collectorPolicy.added(c);
833         if (VALIDATE_SIZE)
834             validateSize("refreshImportance");
835
836     }
837
838     static long loadTime = 0;
839
840     @SuppressWarnings("unchecked")
841     public final <T extends ClusterI> T getClusterProxyByResourceKey(final int resourceKey) {
842         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
843         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
844             throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
845         ClusterI cluster = clusterArray[clusterKey];
846         if (cluster == null)
847             throw new RuntimeException("No proxy for existing cluster. Resource key = " + resourceKey);
848         return (T)cluster;
849     }
850
851     TLongIntHashMap clusterLoadHistogram = new TLongIntHashMap();
852     int clusterLoadCounter = 0;
853
854     private <T extends ClusterI> T ensureLoaded(T c) {
855         ClusterI cluster;
856         ClusterImpl cs = (ClusterImpl) c;
857         try {
858             if(DebugPolicy.REPORT_CLUSTER_LOADING) {
859                 long start = System.nanoTime();
860                 cluster = load2(cs.getClusterId(), cs.getClusterKey());
861                 long load = System.nanoTime()-start;
862                 loadTime +=  load;
863                 if(DebugPolicy.REPORT_CLUSTER_LOADING) {
864                     int was = clusterLoadHistogram.get(cluster.getClusterId());
865                     clusterLoadHistogram.put(cluster.getClusterId(), was+1);
866                     clusterLoadCounter++;
867                     String text = "Load2 " + cluster + " " + 1e-9*loadTime + "s. " + 1e-6*load + "ms. " + clusterLoadCounter + " " + was + " " + cluster.getUsedSpace() + " " + cluster.getImportance();
868                     if(DebugPolicy.REPORT_CLUSTER_LOADING_STACKS) {
869                         new Exception(text).printStackTrace();
870                     } else {
871                         System.err.println(text);
872                     }
873                 }
874             } else {
875                 cluster = load2(cs.getClusterId(), cs.getClusterKey());
876             }
877         } catch (DatabaseException e) {
878             Logger.defaultLogError(e);
879             if (DebugPolicy.REPORT_CLUSTER_EVENTS)
880                 e.printStackTrace();
881             String msg = "Failed to load cluster " + cs.getClusterUID();// + " resourceId=" + (((cs.getClusterId() << 16 + (resourceKey & 65535))));
882             // TODO: this jams the system => needs refactoring.
883             throw new RuntimeDatabaseException(msg, e);
884         }
885         return (T) cluster;
886     }
887     
888     @SuppressWarnings("unchecked")
889     public final <T extends ClusterI> T getClusterByResourceKey(final int resourceKey) {
890         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
891         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
892             throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
893         ClusterI c = clusterArray[clusterKey];
894         if (c == null)
895             return null;
896         if (c.isLoaded()) {
897             if ((counter++ & 4095) == 0)
898                 refreshImportance((ClusterImpl) c);
899             return (T) c;
900         }
901         if (!(c instanceof ClusterSmall)) {
902             Logger.defaultLogError("Proxy must be instance of ClusterSmall");
903             return null;
904         }
905         return ensureLoaded((T)c);
906     }
907
908     @SuppressWarnings("unchecked")
909     final <T extends ClusterI> T checkedGetClusterByResourceKey(final int resourceKey) {
910         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
911         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
912             throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
913         ClusterI c = clusterArray[clusterKey];
914         if (c == null)
915             throw new RuntimeException("No cluster for resource key " + resourceKey);
916         if (c.isLoaded()) {
917             if ((counter++ & 4095) == 0)
918                 refreshImportance((ClusterImpl) c);
919             return (T) c;
920         }
921         if (!(c instanceof ClusterSmall)) {
922             Logger.defaultLogError("Proxy must be instance of ClusterSmall");
923             return null;
924         }
925         ClusterI cluster;
926         ClusterSmall cs = (ClusterSmall) c;
927         try {
928 //          System.err.println("Load2 " + resourceKey);
929             cluster = load2(cs.getClusterId(), cs.getClusterKey());
930         } catch (DatabaseException e) {
931             if (DebugPolicy.REPORT_CLUSTER_EVENTS)
932                 e.printStackTrace();
933             int resourceIndex = resourceKey & ClusterTraitsBase.getResourceIndexFromResourceKeyNoThrow(resourceKey);
934             long resourceId = ClusterTraitsBase.createResourceIdNoThrow(cs.getClusterId(), resourceIndex);
935             String msg = "Failed to load cluster " + cs.getClusterUID() + " for resource key " + resourceKey + " resourceIndex=" + resourceIndex + " resourceId=" + resourceId;
936             Logger.defaultLogError(msg, e);
937             c.setDeleted(true, null);
938             return (T)c;
939         }
940         return (T) cluster;
941     }
942
943     void printDebugInfo(ClusterSupport support)
944             throws DatabaseException {
945         final int SIZE = clusters.size();
946         long sum = 0;
947         for (int i = 1; i < SIZE; ++i) {
948             ClusterI c = clusterArray[i];
949             c.getNumberOfResources(support);
950             long size = c.getUsedSpace();
951             System.out.println("cluster=" + c.getClusterId() + " size=" + size);
952             c.printDebugInfo("koss: ", support);
953             sum += size;
954         }
955         System.out.println("Total number of clusters " + SIZE);
956         System.out.println("Total cluster size " + sum);
957     }
958
959     Map<Long,ClusterImpl> prefetch = new HashMap<Long,ClusterImpl>();
960
961     public synchronized ClusterImpl load2(long clusterId, int clusterKey) throws DatabaseException {
962         ClusterImpl curr = (ClusterImpl) clusterArray[clusterKey];
963         if (curr.isLoaded())
964             return curr;
965
966 //        getPrefetched();
967 //
968 //        curr = (ClusterImpl) clusterArray[clusterKey];
969 //        if (curr.isLoaded())
970 //            return curr;
971
972         final Semaphore s = new Semaphore(0);
973         final DatabaseException[] ex = new DatabaseException[1];
974
975         load2(clusterId, clusterKey, e -> {
976             ex[0] = e;
977             s.release();
978         });
979         try {
980             s.acquire();
981         } catch (InterruptedException e) {
982             Logger.defaultLogError(e);
983         }
984         if (null != ex[0])
985             throw ex[0];
986         if (Development.DEVELOPMENT) {
987             if (Development.<Boolean>getProperty(DevelopmentKeys.CLUSTERTABLE_VALIDATE_ON_LOAD, Bindings.BOOLEAN)) {
988                 try {
989                     ClusterImpl loaded = (ClusterImpl) clusterArray[clusterKey];
990                     if (loaded instanceof ClusterSmall)
991                         ((ClusterSmall) loaded).check();
992                     else if (loaded instanceof ClusterBig)
993                         ((ClusterBig) loaded).check();
994                 } catch (Throwable t) {
995                     t.printStackTrace();
996                 }
997             }
998         }
999         
1000         validate(clusterKey);
1001         
1002         return (ClusterImpl) clusterArray[clusterKey];
1003     }
1004     
1005     void validate(int clusterKey) {
1006         
1007 //      if(sessionImpl.graphSession.graphClient instanceof GraphClientImpl2) {
1008 //          
1009 //        ClusterImpl server = (ClusterImpl)clusterArray[clusterKey]; 
1010 //        String sd = server.dump(sessionImpl.clusterTranslator);
1011 //        GraphClientImpl2 gci = ((GraphClientImpl2)sessionImpl.graphSession.graphClient);
1012 //        ClusterImpl memory = gci.clusters.get(server.clusterUID);
1013 //        if(memory == null)
1014 //            System.err.println("ad");
1015 //        String md = memory.dump(gci.support);
1016 //        
1017 //        if(!sd.equals(md)) {
1018 //            
1019 //            int diffPos = 0;
1020 //            int minLength = Math.min(sd.length(), md.length());
1021 //            for (int i = 0; i < minLength; i++) {
1022 //                if (sd.charAt(i) != md.charAt(i)) {
1023 //                    diffPos = i;
1024 //                    break;
1025 //                }
1026 //            }
1027 //            
1028 //            int start = Math.max(diffPos-200, 0);
1029 //            int end = Math.min(minLength-1, diffPos+200);
1030 //
1031 //            System.err.println("== CLUSTER DIFFERENCE " + clusterArray[clusterKey].getClusterUID() +  " == ");
1032 //            System.err.println("== SESSION == ");
1033 //            System.err.println(sd.substring(start, end));
1034 //            System.err.println("== MEM == ");
1035 //            System.err.println(md.substring(start, end));
1036 //            System.err.println("== CLUSTER DIFFERENCE ENDS == ");
1037 //            
1038 //            throw new IllegalStateException();
1039 //        }
1040 //        
1041 //      }
1042     }
1043
1044     public synchronized ClusterImpl getPrefetched() {
1045         synchronized(prefetch) {
1046             return null;
1047         }
1048     }
1049
1050     public synchronized void load2(long clusterId, int clusterKey, final Consumer<DatabaseException> runnable) {
1051
1052         assert (Constants.ReservedClusterId != clusterId);
1053
1054         ClusterImpl cluster = null;
1055         DatabaseException e = null;
1056
1057         try {
1058
1059             ClusterUID clusterUID = clusters.makeClusterUID(clusterId);
1060 //            cluster = (ClusterImpl) sessionImpl.getGraphSession().getClusterImpl(clusterUID, clusterKey);
1061             Database.Session session = sessionImpl.graphSession.dbSession;
1062 //            cluster = (ClusterImpl)gci.getClusterByClusterKey(clusterKey).clone(sessionImpl.clusterTranslator);
1063 //            cluster = (ClusterImpl)((ClusterImpl)gci.getClusterByClusterUIDOrMakeProxy(clusterUID)).clone(sessionImpl.clusterTranslator);
1064             
1065 //            cluster = gci.clone(clusterUID, sessionImpl.clusterTranslator);
1066             
1067             cluster = session.clone(clusterUID, new ClusterCreator() {
1068                 
1069                 @Override
1070                 public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
1071                     ClusterSupport support = sessionImpl.clusterTranslator;
1072                     try {
1073                         return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
1074                     } catch (DatabaseException e) {
1075                         e.printStackTrace();
1076                         return null;
1077                     }
1078                 }
1079                 
1080             });
1081             
1082         } catch (Throwable t) {
1083             // It's totally legal to call for non-existing cluster.
1084             // Sometimes this indicates an error, though.
1085             Logger.getDefault().logInfo("Load cluster failed.", t);
1086             if (t instanceof DatabaseException)
1087                 e = (DatabaseException) t;
1088             else
1089                 e = new DatabaseException("Load cluster failed.", t);
1090         }
1091         if (null == cluster) {
1092             runnable.accept(e);
1093             return;
1094         }
1095
1096 //      new Exception("Load cluster " + cluster.getClusterId() + " " + cluster.getCachedSize() + " " + cluster.getImmutable()).printStackTrace();
1097
1098         // Can not be called with null argument.
1099         replaceCluster(cluster);
1100         sessionImpl.onClusterLoaded(clusterId);
1101         runnable.accept(null);
1102
1103     }
1104
1105     public synchronized ClusterImpl tryLoad(long clusterId, int clusterKey) throws DatabaseException {
1106
1107         assert (Constants.ReservedClusterId != clusterId);
1108
1109         ClusterUID clusterUID = clusters.makeClusterUID(clusterId);
1110         
1111         Database.Session session = sessionImpl.graphSession.dbSession;
1112         
1113         ClusterImpl cluster = session.clone(clusterUID, new ClusterCreator() {
1114             
1115             @Override
1116             public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
1117                 ClusterSupport support = sessionImpl.clusterTranslator;
1118                 try {
1119                     return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
1120                 } catch (DatabaseException e) {
1121                     e.printStackTrace();
1122                     return null;
1123                 }
1124             }
1125             
1126         });
1127         if (null == clusterArray[clusterKey])
1128             clusterArray[clusterKey] = cluster;
1129         else
1130             replaceCluster(cluster);
1131         sessionImpl.onClusterLoaded(clusterId);
1132         
1133         validate(clusterKey);
1134         
1135         return cluster;
1136     }
1137
1138     public Collection<ClusterI> getClusters() {
1139         ArrayList<ClusterI> result = new ArrayList<ClusterI>();
1140         for (int i = 0; i < clusterArray.length; i++) {
1141             ClusterI cluster = clusterArray[i];
1142             if (cluster != null)
1143                 result.add(cluster);
1144         }
1145         return result;
1146     }
1147
1148     public int size() {
1149         return clusters.size();
1150     }
1151
1152     public long timeCounter() {
1153         return timeCounter.getAndIncrement();
1154     }
1155
1156     public boolean hasVirtual(int index) {
1157         return virtuals[index];
1158     }
1159
1160     public void markVirtual(int index) {
1161         virtuals[index] = true;
1162     }
1163
1164     public ClusterImpl[] getClusterArray() {
1165         return clusterArray;
1166     }
1167
1168     public boolean isImmutable(int id) {
1169
1170         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(id);
1171         Boolean exist = immutables[clusterKey];
1172         if(exist != null) return exist;
1173
1174         ClusterI cluster = getClusterByResourceKey(id);
1175         if(cluster == null) {
1176                 return false;
1177         } else {
1178                 boolean result = cluster.getImmutable();
1179                 markImmutable(cluster, result);
1180                 return result;
1181         }
1182         
1183     }
1184
1185     public void markImmutable(ClusterI cluster, boolean value) {
1186         immutables[cluster.getClusterKey()] = value;
1187     }
1188     @Override
1189     public int getClusterKeyByUID(long first, long second) throws DatabaseException {
1190         return getClusterKeyByClusterUIDOrMakeProxy(ClusterUID.make(first, second));
1191     }
1192
1193     public void adjustCachedSize(long l, ClusterI cluster) {
1194         if (l != 0) {
1195             //System.out.println("ClusterTable: adjusting cluster table cached size by " + l + ": " + sizeInBytes + " -> "
1196             //        + (sizeInBytes + l) + ", for cluster " + cluster.getClusterId() + " (" + cluster + ")");
1197             sizeInBytes += l;
1198         }
1199     }
1200
1201     private void validateSize(String place) {
1202         if (!VALIDATE_SIZE)
1203             return;
1204
1205         int ims = importanceMap.size();
1206         int ihms = countImportantClusters();
1207
1208 //        System.out.format("[ClusterTable.%s] Validating: byteSize=%d (%d MB), hashMap=%d/%d, importanceMap=%d%n",
1209 //                place, sizeInBytes, sizeInBytes / (1024*1024), ihms, clusters.hashMap.size(), ims);
1210
1211         int i = clusterArray.length;
1212         long size = 0;
1213         for (int j = 0; j < i; ++j) {
1214             ClusterI c = clusterArray[j];
1215             if (c == null)
1216                 continue;
1217             size += c.getCachedSize();
1218         }
1219         if (sizeInBytes != size) {
1220             if (!dirtySizeInBytes)
1221                 System.out.println("BUG: CACHED CLUSTER SIZE DIFFERS FROM CALCULATED: " + sizeInBytes + " != " + size + ", delta = " + (sizeInBytes - size));
1222             //else System.out.println("\"BUG?\": SIZES DIFFER: " + sizeInBytes + " != " + size + ", delta = " + (sizeInBytes - size));
1223         }
1224         if (ims != ihms) {
1225             System.out.println("BUG2: hashmap and importanceMap sizes differ: " + ihms + " != " + ims + ", delta=" + (ihms - ims));
1226             printMaps("validateSize");
1227         }
1228         //System.out.println("[" + place + "] VALIDATED");
1229     }
1230
1231     private void printMaps(String place) {
1232         int ihms = countImportantClusters();
1233         System.out.println("## printMaps(" + place + ") - " + importanceMap.size() + " - (" + ihms + "/" + clusters.hashMap.size() + ")");
1234         System.out.println("importanceMap (" + importanceMap.size() + "):");
1235         importanceMap.forEach((importance, ie) -> {
1236             System.out.format("\t%d: %s%n", importance, ie.toString());
1237         });
1238         System.out.println("clusters.hashMap (" + ihms + "/" + clusters.hashMap.size() + "):");
1239         clusters.hashMap.forEachEntry((cid, c) -> {
1240             boolean important = importantCluster(c);
1241             boolean wo = c != null && c.isWriteOnly();
1242             boolean empty = c != null && c.isEmpty();
1243             boolean loaded = c != null && c.isLoaded();
1244             System.out.format("\t%s: %d - %s (writeOnly=%b, empty=%b, loaded=%b)%n", important ? " I" : "NI", cid, c, wo, empty, loaded);
1245             return true;
1246         });
1247     }
1248
1249     private int countImportantClusters() {
1250         int[] result = { 0 };
1251         clusters.hashMap.forEachEntry((cid, c) -> {
1252             if (importantCluster(c))
1253                 result[0]++;
1254             return true;
1255         });
1256         return result[0];
1257     }
1258
1259     private static boolean importantCluster(ClusterImpl c) {
1260         return c != null && !c.isWriteOnly() && c.isLoaded();// && !c.isEmpty();
1261     }
1262
1263 }