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