1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.io.hfile;
20
21 import java.lang.ref.WeakReference;
22 import java.util.EnumMap;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.PriorityQueue;
27 import java.util.SortedSet;
28 import java.util.TreeSet;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.ScheduledExecutorService;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.atomic.AtomicLong;
34 import java.util.concurrent.locks.ReentrantLock;
35
36 import com.google.common.base.Objects;
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39 import org.apache.hadoop.hbase.classification.InterfaceAudience;
40 import org.apache.hadoop.conf.Configuration;
41 import org.apache.hadoop.hbase.io.HeapSize;
42 import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
43 import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache;
44 import org.apache.hadoop.hbase.util.Bytes;
45 import org.apache.hadoop.hbase.util.ClassSize;
46 import org.apache.hadoop.hbase.util.HasThread;
47 import org.apache.hadoop.util.StringUtils;
48
49 import com.google.common.annotations.VisibleForTesting;
50 import com.google.common.util.concurrent.ThreadFactoryBuilder;
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 @InterfaceAudience.Private
97 public class LruBlockCache implements ResizableBlockCache, HeapSize {
98
99 private static final Log LOG = LogFactory.getLog(LruBlockCache.class);
100
101
102
103
104
105 static final String LRU_MIN_FACTOR_CONFIG_NAME = "hbase.lru.blockcache.min.factor";
106
107
108
109
110 static final String LRU_ACCEPTABLE_FACTOR_CONFIG_NAME = "hbase.lru.blockcache.acceptable.factor";
111
112
113
114
115 static final String LRU_HARD_CAPACITY_LIMIT_FACTOR_CONFIG_NAME = "hbase.lru.blockcache.hard.capacity.limit.factor";
116 static final String LRU_SINGLE_PERCENTAGE_CONFIG_NAME = "hbase.lru.blockcache.single.percentage";
117 static final String LRU_MULTI_PERCENTAGE_CONFIG_NAME = "hbase.lru.blockcache.multi.percentage";
118 static final String LRU_MEMORY_PERCENTAGE_CONFIG_NAME = "hbase.lru.blockcache.memory.percentage";
119
120
121
122
123
124
125 static final String LRU_IN_MEMORY_FORCE_MODE_CONFIG_NAME = "hbase.lru.rs.inmemoryforcemode";
126
127
128
129
130 static final float DEFAULT_LOAD_FACTOR = 0.75f;
131 static final int DEFAULT_CONCURRENCY_LEVEL = 16;
132
133
134 static final float DEFAULT_MIN_FACTOR = 0.95f;
135 static final float DEFAULT_ACCEPTABLE_FACTOR = 0.99f;
136
137
138 static final float DEFAULT_SINGLE_FACTOR = 0.25f;
139 static final float DEFAULT_MULTI_FACTOR = 0.50f;
140 static final float DEFAULT_MEMORY_FACTOR = 0.25f;
141
142
143 static final float DEFAULT_HARD_CAPACITY_LIMIT_FACTOR = 1.2f;
144
145 static final boolean DEFAULT_IN_MEMORY_FORCE_MODE = false;
146
147
148 static final int statThreadPeriod = 60 * 5;
149 private static final String LRU_MAX_BLOCK_SIZE = "hbase.lru.max.block.size";
150 private static final long DEFAULT_MAX_BLOCK_SIZE = 16L * 1024L * 1024L;
151
152
153 private transient final Map<BlockCacheKey,LruCachedBlock> map;
154
155
156 private transient final ReentrantLock evictionLock = new ReentrantLock(true);
157 private final long maxBlockSize;
158
159
160 private volatile boolean evictionInProgress = false;
161
162
163 private transient final EvictionThread evictionThread;
164
165
166 private transient final ScheduledExecutorService scheduleThreadPool =
167 Executors.newScheduledThreadPool(1,
168 new ThreadFactoryBuilder().setNameFormat("LruBlockCacheStatsExecutor")
169 .setDaemon(true).build());
170
171
172 private final AtomicLong size;
173
174
175 private final AtomicLong dataBlockSize;
176
177
178 private final AtomicLong elements;
179
180
181 private final AtomicLong dataBlockElements;
182
183
184 private final AtomicLong count;
185
186
187 private float hardCapacityLimitFactor;
188
189
190 private final CacheStats stats;
191
192
193 private long maxSize;
194
195
196 private long blockSize;
197
198
199 private float acceptableFactor;
200
201
202 private float minFactor;
203
204
205 private float singleFactor;
206
207
208 private float multiFactor;
209
210
211 private float memoryFactor;
212
213
214 private long overhead;
215
216
217 private boolean forceInMemory;
218
219
220 private transient BlockCache victimHandler = null;
221
222
223
224
225
226
227
228
229
230
231 public LruBlockCache(long maxSize, long blockSize) {
232 this(maxSize, blockSize, true);
233 }
234
235
236
237
238 public LruBlockCache(long maxSize, long blockSize, boolean evictionThread) {
239 this(maxSize, blockSize, evictionThread,
240 (int)Math.ceil(1.2*maxSize/blockSize),
241 DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL,
242 DEFAULT_MIN_FACTOR, DEFAULT_ACCEPTABLE_FACTOR,
243 DEFAULT_SINGLE_FACTOR,
244 DEFAULT_MULTI_FACTOR,
245 DEFAULT_MEMORY_FACTOR,
246 DEFAULT_HARD_CAPACITY_LIMIT_FACTOR,
247 false,
248 DEFAULT_MAX_BLOCK_SIZE
249 );
250 }
251
252 public LruBlockCache(long maxSize, long blockSize, boolean evictionThread, Configuration conf) {
253 this(maxSize, blockSize, evictionThread,
254 (int)Math.ceil(1.2*maxSize/blockSize),
255 DEFAULT_LOAD_FACTOR,
256 DEFAULT_CONCURRENCY_LEVEL,
257 conf.getFloat(LRU_MIN_FACTOR_CONFIG_NAME, DEFAULT_MIN_FACTOR),
258 conf.getFloat(LRU_ACCEPTABLE_FACTOR_CONFIG_NAME, DEFAULT_ACCEPTABLE_FACTOR),
259 conf.getFloat(LRU_SINGLE_PERCENTAGE_CONFIG_NAME, DEFAULT_SINGLE_FACTOR),
260 conf.getFloat(LRU_MULTI_PERCENTAGE_CONFIG_NAME, DEFAULT_MULTI_FACTOR),
261 conf.getFloat(LRU_MEMORY_PERCENTAGE_CONFIG_NAME, DEFAULT_MEMORY_FACTOR),
262 conf.getFloat(LRU_HARD_CAPACITY_LIMIT_FACTOR_CONFIG_NAME, DEFAULT_HARD_CAPACITY_LIMIT_FACTOR),
263 conf.getBoolean(LRU_IN_MEMORY_FORCE_MODE_CONFIG_NAME, DEFAULT_IN_MEMORY_FORCE_MODE),
264 conf.getLong(LRU_MAX_BLOCK_SIZE, DEFAULT_MAX_BLOCK_SIZE)
265 );
266 }
267
268 public LruBlockCache(long maxSize, long blockSize, Configuration conf) {
269 this(maxSize, blockSize, true, conf);
270 }
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286 public LruBlockCache(long maxSize, long blockSize, boolean evictionThread,
287 int mapInitialSize, float mapLoadFactor, int mapConcurrencyLevel,
288 float minFactor, float acceptableFactor, float singleFactor,
289 float multiFactor, float memoryFactor, float hardLimitFactor,
290 boolean forceInMemory, long maxBlockSize) {
291 this.maxBlockSize = maxBlockSize;
292 if(singleFactor + multiFactor + memoryFactor != 1 ||
293 singleFactor < 0 || multiFactor < 0 || memoryFactor < 0) {
294 throw new IllegalArgumentException("Single, multi, and memory factors " +
295 " should be non-negative and total 1.0");
296 }
297 if(minFactor >= acceptableFactor) {
298 throw new IllegalArgumentException("minFactor must be smaller than acceptableFactor");
299 }
300 if(minFactor >= 1.0f || acceptableFactor >= 1.0f) {
301 throw new IllegalArgumentException("all factors must be < 1");
302 }
303 this.maxSize = maxSize;
304 this.blockSize = blockSize;
305 this.forceInMemory = forceInMemory;
306 map = new ConcurrentHashMap<BlockCacheKey,LruCachedBlock>(mapInitialSize,
307 mapLoadFactor, mapConcurrencyLevel);
308 this.minFactor = minFactor;
309 this.acceptableFactor = acceptableFactor;
310 this.singleFactor = singleFactor;
311 this.multiFactor = multiFactor;
312 this.memoryFactor = memoryFactor;
313 this.stats = new CacheStats(this.getClass().getSimpleName());
314 this.count = new AtomicLong(0);
315 this.elements = new AtomicLong(0);
316 this.dataBlockElements = new AtomicLong(0);
317 this.dataBlockSize = new AtomicLong(0);
318 this.overhead = calculateOverhead(maxSize, blockSize, mapConcurrencyLevel);
319 this.size = new AtomicLong(this.overhead);
320 this.hardCapacityLimitFactor = hardLimitFactor;
321 if(evictionThread) {
322 this.evictionThread = new EvictionThread(this);
323 this.evictionThread.start();
324 } else {
325 this.evictionThread = null;
326 }
327
328
329 this.scheduleThreadPool.scheduleAtFixedRate(new StatisticsThread(this),
330 statThreadPeriod, statThreadPeriod, TimeUnit.SECONDS);
331 }
332
333 @Override
334 public void setMaxSize(long maxSize) {
335 this.maxSize = maxSize;
336 if(this.size.get() > acceptableSize() && !evictionInProgress) {
337 runEviction();
338 }
339 }
340
341
342
343
344
345
346
347
348
349
350
351
352
353 @Override
354 public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory,
355 final boolean cacheDataInL1) {
356
357 if (buf.heapSize() > maxBlockSize) {
358
359
360
361 if (stats.failInsert() % 50 == 0) {
362 LOG.warn("Trying to cache too large a block "
363 + cacheKey.getHfileName() + " @ "
364 + cacheKey.getOffset()
365 + " is " + buf.heapSize()
366 + " which is larger than " + maxBlockSize);
367 }
368 return;
369 }
370
371 LruCachedBlock cb = map.get(cacheKey);
372 if (!cacheDataInL1 && cb != null
373 && !BlockCacheUtil.shouldReplaceExistingCacheBlock(this, cacheKey, buf)) {
374 return;
375 }
376 long currentSize = size.get();
377 long currentAcceptableSize = acceptableSize();
378 long hardLimitSize = (long) (hardCapacityLimitFactor * currentAcceptableSize);
379 if (currentSize >= hardLimitSize) {
380 stats.failInsert();
381 if (LOG.isTraceEnabled()) {
382 LOG.trace("LruBlockCache current size " + StringUtils.byteDesc(currentSize)
383 + " has exceeded acceptable size " + StringUtils.byteDesc(currentAcceptableSize) + " too many."
384 + " the hard limit size is " + StringUtils.byteDesc(hardLimitSize) + ", failed to put cacheKey:"
385 + cacheKey + " into LruBlockCache.");
386 }
387 if (!evictionInProgress) {
388 runEviction();
389 }
390 return;
391 }
392 cb = new LruCachedBlock(cacheKey, buf, count.incrementAndGet(), inMemory);
393 long newSize = updateSizeMetrics(cb, false);
394 map.put(cacheKey, cb);
395 long val = elements.incrementAndGet();
396 if (buf.getBlockType().isData()) {
397 dataBlockElements.incrementAndGet();
398 }
399 if (LOG.isTraceEnabled()) {
400 long size = map.size();
401 assertCounterSanity(size, val);
402 }
403 if (newSize > currentAcceptableSize && !evictionInProgress) {
404 runEviction();
405 }
406 }
407
408
409
410
411
412 private static void assertCounterSanity(long mapSize, long counterVal) {
413 if (counterVal < 0) {
414 LOG.trace("counterVal overflow. Assertions unreliable. counterVal=" + counterVal +
415 ", mapSize=" + mapSize);
416 return;
417 }
418 if (mapSize < Integer.MAX_VALUE) {
419 double pct_diff = Math.abs((((double) counterVal) / ((double) mapSize)) - 1.);
420 if (pct_diff > 0.05) {
421 LOG.trace("delta between reported and actual size > 5%. counterVal=" + counterVal +
422 ", mapSize=" + mapSize);
423 }
424 }
425 }
426
427
428
429
430
431
432
433 @Override
434 public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) {
435 cacheBlock(cacheKey, buf, false, false);
436 }
437
438
439
440
441
442
443
444
445
446 protected long updateSizeMetrics(LruCachedBlock cb, boolean evict) {
447 long heapsize = cb.heapSize();
448 BlockType bt = cb.getBuffer().getBlockType();
449 if (evict) {
450 heapsize *= -1;
451 }
452 if (bt != null && bt.isData()) {
453 dataBlockSize.addAndGet(heapsize);
454 }
455 return size.addAndGet(heapsize);
456 }
457
458
459
460
461
462
463
464
465
466
467 @Override
468 public Cacheable getBlock(BlockCacheKey cacheKey, boolean caching, boolean repeat,
469 boolean updateCacheMetrics) {
470 LruCachedBlock cb = map.get(cacheKey);
471 if (cb == null) {
472 if (!repeat && updateCacheMetrics) {
473 stats.miss(caching, cacheKey.isPrimary(), cacheKey.getBlockType());
474 }
475
476
477
478 if (victimHandler != null && !repeat) {
479 Cacheable result = victimHandler.getBlock(cacheKey, caching, repeat, updateCacheMetrics);
480
481
482 if (result != null && caching) {
483 cacheBlock(cacheKey, result, false, true);
484 }
485 return result;
486 }
487 return null;
488 }
489 if (updateCacheMetrics) stats.hit(caching, cacheKey.isPrimary(), cacheKey.getBlockType());
490 cb.access(count.incrementAndGet());
491 return cb.getBuffer();
492 }
493
494
495
496
497
498
499 public boolean containsBlock(BlockCacheKey cacheKey) {
500 return map.containsKey(cacheKey);
501 }
502
503 @Override
504 public boolean evictBlock(BlockCacheKey cacheKey) {
505 LruCachedBlock cb = map.get(cacheKey);
506 if (cb == null) return false;
507 return evictBlock(cb, false) > 0;
508 }
509
510
511
512
513
514
515
516
517
518
519
520 @Override
521 public int evictBlocksByHfileName(String hfileName) {
522 int numEvicted = 0;
523 for (BlockCacheKey key : map.keySet()) {
524 if (key.getHfileName().equals(hfileName)) {
525 if (evictBlock(key))
526 ++numEvicted;
527 }
528 }
529 if (victimHandler != null) {
530 numEvicted += victimHandler.evictBlocksByHfileName(hfileName);
531 }
532 return numEvicted;
533 }
534
535
536
537
538
539
540
541
542
543 protected long evictBlock(LruCachedBlock block, boolean evictedByEvictionProcess) {
544 boolean found = map.remove(block.getCacheKey()) != null;
545 if (!found) {
546 return 0;
547 }
548 updateSizeMetrics(block, true);
549 long val = elements.decrementAndGet();
550 if (LOG.isTraceEnabled()) {
551 long size = map.size();
552 assertCounterSanity(size, val);
553 }
554 if (block.getBuffer().getBlockType().isData()) {
555 dataBlockElements.decrementAndGet();
556 }
557 stats.evicted(block.getCachedTime(), block.getCacheKey().isPrimary());
558 if (evictedByEvictionProcess && victimHandler != null) {
559 if (victimHandler instanceof BucketCache) {
560 boolean wait = getCurrentSize() < acceptableSize();
561 boolean inMemory = block.getPriority() == BlockPriority.MEMORY;
562 ((BucketCache)victimHandler).cacheBlockWithWait(block.getCacheKey(), block.getBuffer(),
563 inMemory, true, wait);
564 } else {
565 victimHandler.cacheBlock(block.getCacheKey(), block.getBuffer());
566 }
567 }
568 return block.heapSize();
569 }
570
571
572
573
574 private void runEviction() {
575 if(evictionThread == null) {
576 evict();
577 } else {
578 evictionThread.evict();
579 }
580 }
581
582 @VisibleForTesting
583 boolean isEvictionInProgress() {
584 return evictionInProgress;
585 }
586
587 @VisibleForTesting
588 long getOverhead() {
589 return overhead;
590 }
591
592
593
594
595 void evict() {
596
597
598 if(!evictionLock.tryLock()) return;
599
600 try {
601 evictionInProgress = true;
602 long currentSize = this.size.get();
603 long bytesToFree = currentSize - minSize();
604
605 if (LOG.isTraceEnabled()) {
606 LOG.trace("Block cache LRU eviction started; Attempting to free " +
607 StringUtils.byteDesc(bytesToFree) + " of total=" +
608 StringUtils.byteDesc(currentSize));
609 }
610
611 if(bytesToFree <= 0) return;
612
613
614 BlockBucket bucketSingle = new BlockBucket("single", bytesToFree, blockSize,
615 singleSize());
616 BlockBucket bucketMulti = new BlockBucket("multi", bytesToFree, blockSize,
617 multiSize());
618 BlockBucket bucketMemory = new BlockBucket("memory", bytesToFree, blockSize,
619 memorySize());
620
621
622 for(LruCachedBlock cachedBlock : map.values()) {
623 switch(cachedBlock.getPriority()) {
624 case SINGLE: {
625 bucketSingle.add(cachedBlock);
626 break;
627 }
628 case MULTI: {
629 bucketMulti.add(cachedBlock);
630 break;
631 }
632 case MEMORY: {
633 bucketMemory.add(cachedBlock);
634 break;
635 }
636 }
637 }
638
639 long bytesFreed = 0;
640 if (forceInMemory || memoryFactor > 0.999f) {
641 long s = bucketSingle.totalSize();
642 long m = bucketMulti.totalSize();
643 if (bytesToFree > (s + m)) {
644
645
646 bytesFreed = bucketSingle.free(s);
647 bytesFreed += bucketMulti.free(m);
648 if (LOG.isTraceEnabled()) {
649 LOG.trace("freed " + StringUtils.byteDesc(bytesFreed) +
650 " from single and multi buckets");
651 }
652 bytesFreed += bucketMemory.free(bytesToFree - bytesFreed);
653 if (LOG.isTraceEnabled()) {
654 LOG.trace("freed " + StringUtils.byteDesc(bytesFreed) +
655 " total from all three buckets ");
656 }
657 } else {
658
659
660
661 long bytesRemain = s + m - bytesToFree;
662 if (3 * s <= bytesRemain) {
663
664
665 bytesFreed = bucketMulti.free(bytesToFree);
666 } else if (3 * m <= 2 * bytesRemain) {
667
668
669 bytesFreed = bucketSingle.free(bytesToFree);
670 } else {
671
672 bytesFreed = bucketSingle.free(s - bytesRemain / 3);
673 if (bytesFreed < bytesToFree) {
674 bytesFreed += bucketMulti.free(bytesToFree - bytesFreed);
675 }
676 }
677 }
678 } else {
679 PriorityQueue<BlockBucket> bucketQueue =
680 new PriorityQueue<BlockBucket>(3);
681
682 bucketQueue.add(bucketSingle);
683 bucketQueue.add(bucketMulti);
684 bucketQueue.add(bucketMemory);
685
686 int remainingBuckets = bucketQueue.size();
687
688 BlockBucket bucket;
689 while((bucket = bucketQueue.poll()) != null) {
690 long overflow = bucket.overflow();
691 if(overflow > 0) {
692 long bucketBytesToFree = Math.min(overflow,
693 (bytesToFree - bytesFreed) / remainingBuckets);
694 bytesFreed += bucket.free(bucketBytesToFree);
695 }
696 remainingBuckets--;
697 }
698 }
699 if (LOG.isTraceEnabled()) {
700 long single = bucketSingle.totalSize();
701 long multi = bucketMulti.totalSize();
702 long memory = bucketMemory.totalSize();
703 LOG.trace("Block cache LRU eviction completed; " +
704 "freed=" + StringUtils.byteDesc(bytesFreed) + ", " +
705 "total=" + StringUtils.byteDesc(this.size.get()) + ", " +
706 "single=" + StringUtils.byteDesc(single) + ", " +
707 "multi=" + StringUtils.byteDesc(multi) + ", " +
708 "memory=" + StringUtils.byteDesc(memory));
709 }
710 } finally {
711 stats.evict();
712 evictionInProgress = false;
713 evictionLock.unlock();
714 }
715 }
716
717 @Override
718 public String toString() {
719 return Objects.toStringHelper(this)
720 .add("blockCount", getBlockCount())
721 .add("currentSize", getCurrentSize())
722 .add("freeSize", getFreeSize())
723 .add("maxSize", getMaxSize())
724 .add("heapSize", heapSize())
725 .add("minSize", minSize())
726 .add("minFactor", minFactor)
727 .add("multiSize", multiSize())
728 .add("multiFactor", multiFactor)
729 .add("singleSize", singleSize())
730 .add("singleFactor", singleFactor)
731 .toString();
732 }
733
734
735
736
737
738
739
740 private class BlockBucket implements Comparable<BlockBucket> {
741
742 private final String name;
743 private LruCachedBlockQueue queue;
744 private long totalSize = 0;
745 private long bucketSize;
746
747 public BlockBucket(String name, long bytesToFree, long blockSize, long bucketSize) {
748 this.name = name;
749 this.bucketSize = bucketSize;
750 queue = new LruCachedBlockQueue(bytesToFree, blockSize);
751 totalSize = 0;
752 }
753
754 public void add(LruCachedBlock block) {
755 totalSize += block.heapSize();
756 queue.add(block);
757 }
758
759 public long free(long toFree) {
760 if (LOG.isTraceEnabled()) {
761 LOG.trace("freeing " + StringUtils.byteDesc(toFree) + " from " + this);
762 }
763 LruCachedBlock cb;
764 long freedBytes = 0;
765 while ((cb = queue.pollLast()) != null) {
766 freedBytes += evictBlock(cb, true);
767 if (freedBytes >= toFree) {
768 return freedBytes;
769 }
770 }
771 if (LOG.isTraceEnabled()) {
772 LOG.trace("freed " + StringUtils.byteDesc(freedBytes) + " from " + this);
773 }
774 return freedBytes;
775 }
776
777 public long overflow() {
778 return totalSize - bucketSize;
779 }
780
781 public long totalSize() {
782 return totalSize;
783 }
784
785 @Override
786 public int compareTo(BlockBucket that) {
787 return Long.compare(this.overflow(), that.overflow());
788 }
789
790 @Override
791 public boolean equals(Object that) {
792 if (that == null || !(that instanceof BlockBucket)){
793 return false;
794 }
795 return compareTo((BlockBucket)that) == 0;
796 }
797
798 @Override
799 public int hashCode() {
800 return Objects.hashCode(name, bucketSize, queue, totalSize);
801 }
802
803 @Override
804 public String toString() {
805 return Objects.toStringHelper(this)
806 .add("name", name)
807 .add("totalSize", StringUtils.byteDesc(totalSize))
808 .add("bucketSize", StringUtils.byteDesc(bucketSize))
809 .toString();
810 }
811 }
812
813
814
815
816
817
818 @Override
819 public long getMaxSize() {
820 return this.maxSize;
821 }
822
823 @Override
824 public long getCurrentSize() {
825 return this.size.get();
826 }
827
828 @Override
829 public long getCurrentDataSize() {
830 return this.dataBlockSize.get();
831 }
832
833 @Override
834 public long getFreeSize() {
835 return getMaxSize() - getCurrentSize();
836 }
837
838 @Override
839 public long size() {
840 return getMaxSize();
841 }
842
843 @Override
844 public long getBlockCount() {
845 return this.elements.get();
846 }
847
848 @Override
849 public long getDataBlockCount() {
850 return this.dataBlockElements.get();
851 }
852
853 EvictionThread getEvictionThread() {
854 return this.evictionThread;
855 }
856
857
858
859
860
861
862
863 static class EvictionThread extends HasThread {
864 private WeakReference<LruBlockCache> cache;
865 private volatile boolean go = true;
866
867 private boolean enteringRun = false;
868
869 public EvictionThread(LruBlockCache cache) {
870 super(Thread.currentThread().getName() + ".LruBlockCache.EvictionThread");
871 setDaemon(true);
872 this.cache = new WeakReference<LruBlockCache>(cache);
873 }
874
875 @Override
876 public void run() {
877 enteringRun = true;
878 while (this.go) {
879 synchronized(this) {
880 try {
881 this.wait(1000 * 10
882 } catch(InterruptedException e) {
883 LOG.warn("Interrupted eviction thread ", e);
884 Thread.currentThread().interrupt();
885 }
886 }
887 LruBlockCache cache = this.cache.get();
888 if (cache == null) break;
889 cache.evict();
890 }
891 }
892
893 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NN_NAKED_NOTIFY",
894 justification="This is what we want")
895 public void evict() {
896 synchronized(this) {
897 this.notifyAll();
898 }
899 }
900
901 synchronized void shutdown() {
902 this.go = false;
903 this.notifyAll();
904 }
905
906
907
908
909 boolean isEnteringRun() {
910 return this.enteringRun;
911 }
912 }
913
914
915
916
917 static class StatisticsThread extends Thread {
918 private final LruBlockCache lru;
919
920 public StatisticsThread(LruBlockCache lru) {
921 super("LruBlockCacheStats");
922 setDaemon(true);
923 this.lru = lru;
924 }
925
926 @Override
927 public void run() {
928 lru.logStats();
929 }
930 }
931
932 public void logStats() {
933
934 long totalSize = heapSize();
935 long freeSize = maxSize - totalSize;
936 LruBlockCache.LOG.info("totalSize=" + StringUtils.byteDesc(totalSize) + ", " +
937 "freeSize=" + StringUtils.byteDesc(freeSize) + ", " +
938 "max=" + StringUtils.byteDesc(this.maxSize) + ", " +
939 "blockCount=" + getBlockCount() + ", " +
940 "accesses=" + stats.getRequestCount() + ", " +
941 "hits=" + stats.getHitCount() + ", " +
942 "hitRatio=" + (stats.getHitCount() == 0 ?
943 "0" : (StringUtils.formatPercent(stats.getHitRatio(), 2)+ ", ")) + ", " +
944 "cachingAccesses=" + stats.getRequestCachingCount() + ", " +
945 "cachingHits=" + stats.getHitCachingCount() + ", " +
946 "cachingHitsRatio=" + (stats.getHitCachingCount() == 0 ?
947 "0,": (StringUtils.formatPercent(stats.getHitCachingRatio(), 2) + ", ")) +
948 "evictions=" + stats.getEvictionCount() + ", " +
949 "evicted=" + stats.getEvictedCount() + ", " +
950 "evictedPerRun=" + stats.evictedPerEviction());
951 }
952
953
954
955
956
957
958
959 @Override
960 public CacheStats getStats() {
961 return this.stats;
962 }
963
964 public final static long CACHE_FIXED_OVERHEAD = ClassSize.align(
965 (4 * Bytes.SIZEOF_LONG) + (11 * ClassSize.REFERENCE) +
966 (6 * Bytes.SIZEOF_FLOAT) + (2 * Bytes.SIZEOF_BOOLEAN)
967 + ClassSize.OBJECT);
968
969 @Override
970 public long heapSize() {
971 return getCurrentSize();
972 }
973
974 public static long calculateOverhead(long maxSize, long blockSize, int concurrency){
975
976 return CACHE_FIXED_OVERHEAD + ClassSize.CONCURRENT_HASHMAP +
977 ((long)Math.ceil(maxSize*1.2/blockSize)
978 * ClassSize.CONCURRENT_HASHMAP_ENTRY) +
979 ((long)concurrency * ClassSize.CONCURRENT_HASHMAP_SEGMENT);
980 }
981
982 @Override
983 public Iterator<CachedBlock> iterator() {
984 final Iterator<LruCachedBlock> iterator = map.values().iterator();
985
986 return new Iterator<CachedBlock>() {
987 private final long now = System.nanoTime();
988
989 @Override
990 public boolean hasNext() {
991 return iterator.hasNext();
992 }
993
994 @Override
995 public CachedBlock next() {
996 final LruCachedBlock b = iterator.next();
997 return new CachedBlock() {
998 @Override
999 public String toString() {
1000 return BlockCacheUtil.toString(this, now);
1001 }
1002
1003 @Override
1004 public BlockPriority getBlockPriority() {
1005 return b.getPriority();
1006 }
1007
1008 @Override
1009 public BlockType getBlockType() {
1010 return b.getBuffer().getBlockType();
1011 }
1012
1013 @Override
1014 public long getOffset() {
1015 return b.getCacheKey().getOffset();
1016 }
1017
1018 @Override
1019 public long getSize() {
1020 return b.getBuffer().heapSize();
1021 }
1022
1023 @Override
1024 public long getCachedTime() {
1025 return b.getCachedTime();
1026 }
1027
1028 @Override
1029 public String getFilename() {
1030 return b.getCacheKey().getHfileName();
1031 }
1032
1033 @Override
1034 public int compareTo(CachedBlock other) {
1035 int diff = this.getFilename().compareTo(other.getFilename());
1036 if (diff != 0) return diff;
1037 diff = Long.compare(this.getOffset(), other.getOffset());
1038 if (diff != 0) return diff;
1039 if (other.getCachedTime() < 0 || this.getCachedTime() < 0) {
1040 throw new IllegalStateException("" + this.getCachedTime() + ", " +
1041 other.getCachedTime());
1042 }
1043 return Long.compare(other.getCachedTime(), this.getCachedTime());
1044 }
1045
1046 @Override
1047 public int hashCode() {
1048 return b.hashCode();
1049 }
1050
1051 @Override
1052 public boolean equals(Object obj) {
1053 if (obj instanceof CachedBlock) {
1054 CachedBlock cb = (CachedBlock)obj;
1055 return compareTo(cb) == 0;
1056 } else {
1057 return false;
1058 }
1059 }
1060 };
1061 }
1062
1063 @Override
1064 public void remove() {
1065 throw new UnsupportedOperationException();
1066 }
1067 };
1068 }
1069
1070
1071
1072 long acceptableSize() {
1073 return (long)Math.floor(this.maxSize * this.acceptableFactor);
1074 }
1075
1076 private long minSize() {
1077 return (long)Math.floor(this.maxSize * this.minFactor);
1078 }
1079
1080 private long singleSize() {
1081 return (long)Math.floor(this.maxSize * this.singleFactor * this.minFactor);
1082 }
1083
1084 private long multiSize() {
1085 return (long)Math.floor(this.maxSize * this.multiFactor * this.minFactor);
1086 }
1087
1088 private long memorySize() {
1089 return (long)Math.floor(this.maxSize * this.memoryFactor * this.minFactor);
1090 }
1091
1092 @Override
1093 public void shutdown() {
1094 if (victimHandler != null)
1095 victimHandler.shutdown();
1096 this.scheduleThreadPool.shutdown();
1097 for (int i = 0; i < 10; i++) {
1098 if (!this.scheduleThreadPool.isShutdown()) {
1099 try {
1100 Thread.sleep(10);
1101 } catch (InterruptedException e) {
1102 LOG.warn("Interrupted while sleeping");
1103 Thread.currentThread().interrupt();
1104 break;
1105 }
1106 }
1107 }
1108
1109 if (!this.scheduleThreadPool.isShutdown()) {
1110 List<Runnable> runnables = this.scheduleThreadPool.shutdownNow();
1111 LOG.debug("Still running " + runnables);
1112 }
1113 this.evictionThread.shutdown();
1114 }
1115
1116
1117 @VisibleForTesting
1118 public void clearCache() {
1119 this.map.clear();
1120 this.elements.set(0);
1121 }
1122
1123
1124
1125
1126
1127 @VisibleForTesting
1128 SortedSet<String> getCachedFileNamesForTest() {
1129 SortedSet<String> fileNames = new TreeSet<String>();
1130 for (BlockCacheKey cacheKey : map.keySet()) {
1131 fileNames.add(cacheKey.getHfileName());
1132 }
1133 return fileNames;
1134 }
1135
1136 @VisibleForTesting
1137 Map<BlockType, Integer> getBlockTypeCountsForTest() {
1138 Map<BlockType, Integer> counts =
1139 new EnumMap<BlockType, Integer>(BlockType.class);
1140 for (LruCachedBlock cb : map.values()) {
1141 BlockType blockType = ((Cacheable)cb.getBuffer()).getBlockType();
1142 Integer count = counts.get(blockType);
1143 counts.put(blockType, (count == null ? 0 : count) + 1);
1144 }
1145 return counts;
1146 }
1147
1148 @VisibleForTesting
1149 public Map<DataBlockEncoding, Integer> getEncodingCountsForTest() {
1150 Map<DataBlockEncoding, Integer> counts =
1151 new EnumMap<DataBlockEncoding, Integer>(DataBlockEncoding.class);
1152 for (LruCachedBlock block : map.values()) {
1153 DataBlockEncoding encoding =
1154 ((HFileBlock) block.getBuffer()).getDataBlockEncoding();
1155 Integer count = counts.get(encoding);
1156 counts.put(encoding, (count == null ? 0 : count) + 1);
1157 }
1158 return counts;
1159 }
1160
1161 public void setVictimCache(BlockCache handler) {
1162 assert victimHandler == null;
1163 victimHandler = handler;
1164 }
1165
1166 @VisibleForTesting
1167 Map<BlockCacheKey, LruCachedBlock> getMapForTests() {
1168 return map;
1169 }
1170
1171 BlockCache getVictimHandler() {
1172 return this.victimHandler;
1173 }
1174
1175 @Override
1176 public BlockCache[] getBlockCaches() {
1177 if (victimHandler != null) {
1178 return new BlockCache[]{this, this.victimHandler};
1179 }
1180 return null;
1181 }
1182 }