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