View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
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   * A block cache implementation that is memory-aware using {@link HeapSize},
60   * memory-bound using an LRU eviction algorithm, and concurrent: backed by a
61   * {@link ConcurrentHashMap} and with a non-blocking eviction thread giving
62   * constant-time {@link #cacheBlock} and {@link #getBlock} operations.<p>
63   *
64   * Contains three levels of block priority to allow for
65   * scan-resistance and in-memory families 
66   * {@link org.apache.hadoop.hbase.HColumnDescriptor#setInMemory(boolean)} (An
67   * in-memory column family is a column family that should be served from memory if possible):
68   * single-access, multiple-accesses, and in-memory priority.
69   * A block is added with an in-memory priority flag if
70   * {@link org.apache.hadoop.hbase.HColumnDescriptor#isInMemory()}, 
71   * otherwise a block becomes a single access
72   * priority the first time it is read into this block cache.  If a block is accessed again while
73   * in cache, it is marked as a multiple access priority block.  This delineation of blocks is used
74   * to prevent scans from thrashing the cache adding a least-frequently-used
75   * element to the eviction algorithm.<p>
76   *
77   * Each priority is given its own chunk of the total cache to ensure
78   * fairness during eviction.  Each priority will retain close to its maximum
79   * size, however, if any priority is not using its entire chunk the others
80   * are able to grow beyond their chunk size.<p>
81   *
82   * Instantiated at a minimum with the total size and average block size.
83   * All sizes are in bytes.  The block size is not especially important as this
84   * cache is fully dynamic in its sizing of blocks.  It is only used for
85   * pre-allocating data structures and in initial heap estimation of the map.<p>
86   *
87   * The detailed constructor defines the sizes for the three priorities (they
88   * should total to the <code>maximum size</code> defined).  It also sets the levels that
89   * trigger and control the eviction thread.<p>
90   *
91   * The <code>acceptable size</code> is the cache size level which triggers the eviction
92   * process to start.  It evicts enough blocks to get the size below the
93   * minimum size specified.<p>
94   *
95   * Eviction happens in a separate thread and involves a single full-scan
96   * of the map.  It determines how many bytes must be freed to reach the minimum
97   * size, and then while scanning determines the fewest least-recently-used
98   * blocks necessary from each of the three priorities (would be 3 times bytes
99   * to free).  It then uses the priority chunk sizes to evict fairly according
100  * to the relative sizes and usage.
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    * Percentage of total size that eviction will evict until; e.g. if set to .8, then we will keep
109    * evicting during an eviction run till the cache size is down to 80% of the total.
110    */
111   static final String LRU_MIN_FACTOR_CONFIG_NAME = "hbase.lru.blockcache.min.factor";
112 
113   /**
114    * Acceptable size of cache (no evictions if size < acceptable)
115    */
116   static final String LRU_ACCEPTABLE_FACTOR_CONFIG_NAME = "hbase.lru.blockcache.acceptable.factor";
117 
118   /**
119    * Hard capacity limit of cache, will reject any put if size > this * acceptable
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    * Configuration key to force data-block always (except in-memory are too much)
128    * cached in memory for in-memory hfile, unlike inMemory, which is a column-family
129    * configuration, inMemoryForceMode is a cluster-wide configuration
130    */
131   static final String LRU_IN_MEMORY_FORCE_MODE_CONFIG_NAME = "hbase.lru.rs.inmemoryforcemode";
132 
133   /** Default Configuration Parameters*/
134 
135   /** Backing Concurrent Map Configuration */
136   static final float DEFAULT_LOAD_FACTOR = 0.75f;
137   static final int DEFAULT_CONCURRENCY_LEVEL = 16;
138 
139   /** Eviction thresholds */
140   static final float DEFAULT_MIN_FACTOR = 0.95f;
141   static final float DEFAULT_ACCEPTABLE_FACTOR = 0.99f;
142 
143   /** Priority buckets */
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   /** default hard capacity limit */
149   static final float DEFAULT_HARD_CAPACITY_LIMIT_FACTOR = 1.2f;
150 
151   static final boolean DEFAULT_IN_MEMORY_FORCE_MODE = false;
152 
153   /** Statistics thread */
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   /** Concurrent map (the cache) */
159   private transient final Map<BlockCacheKey,LruCachedBlock> map;
160 
161   /** Eviction lock (locked when eviction in process) */
162   private transient final ReentrantLock evictionLock = new ReentrantLock(true);
163   private final long maxBlockSize;
164 
165   /** Volatile boolean to track if we are in an eviction process or not */
166   private volatile boolean evictionInProgress = false;
167 
168   /** Eviction thread */
169   private transient final EvictionThread evictionThread;
170 
171   /** Statistics thread schedule pool (for heavy debugging, could remove) */
172   private transient final ScheduledExecutorService scheduleThreadPool =
173     Executors.newScheduledThreadPool(1,
174       new ThreadFactoryBuilder().setNameFormat("LruBlockCacheStatsExecutor")
175         .setDaemon(true).build());
176 
177   /** Current size of cache */
178   private final AtomicLong size;
179 
180   /** Current number of cached elements */
181   private final AtomicLong elements;
182 
183   /** Cache access count (sequential ID) */
184   private final AtomicLong count;
185 
186   /** hard capacity limit */
187   private float hardCapacityLimitFactor;
188 
189   /** Cache statistics */
190   private final CacheStats stats;
191 
192   /** Maximum allowable size of cache (block put if size > max, evict) */
193   private long maxSize;
194 
195   /** Approximate block size */
196   private long blockSize;
197 
198   /** Acceptable size of cache (no evictions if size < acceptable) */
199   private float acceptableFactor;
200 
201   /** Minimum threshold of cache (when evicting, evict until size < min) */
202   private float minFactor;
203 
204   /** Single access bucket size */
205   private float singleFactor;
206 
207   /** Multiple access bucket size */
208   private float multiFactor;
209 
210   /** In-memory bucket size */
211   private float memoryFactor;
212 
213   /** Overhead of the structure itself */
214   private long overhead;
215 
216   /** Whether in-memory hfile's data block has higher priority when evicting */
217   private boolean forceInMemory;
218 
219   /** Where to send victims (blocks evicted/missing from the cache) */
220   private transient BlockCache victimHandler = null;
221 
222   /**
223    * Default constructor.  Specify maximum size and expected average block
224    * size (approximation is fine).
225    *
226    * <p>All other factors will be calculated based on defaults specified in
227    * this class.
228    * @param maxSize maximum size of cache, in bytes
229    * @param blockSize approximate size of each block, in bytes
230    */
231   public LruBlockCache(long maxSize, long blockSize) {
232     this(maxSize, blockSize, true);
233   }
234 
235   /**
236    * Constructor used for testing.  Allows disabling of the eviction thread.
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    * Configurable constructor.  Use this constructor if not using defaults.
274    * @param maxSize maximum size of this cache, in bytes
275    * @param blockSize expected average size of blocks, in bytes
276    * @param evictionThread whether to run evictions in a bg thread or not
277    * @param mapInitialSize initial size of backing ConcurrentHashMap
278    * @param mapLoadFactor initial load factor of backing ConcurrentHashMap
279    * @param mapConcurrencyLevel initial concurrency factor for backing CHM
280    * @param minFactor percentage of total size that eviction will evict until
281    * @param acceptableFactor percentage of total size that triggers eviction
282    * @param singleFactor percentage of total size for single-access blocks
283    * @param multiFactor percentage of total size for multiple-access blocks
284    * @param memoryFactor percentage of total size for in-memory blocks
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(); // FindBugs SC_START_IN_CTOR
322     } else {
323       this.evictionThread = null;
324     }
325     // TODO: Add means of turning this off.  Bit obnoxious running thread just to make a log
326     // every five minutes.
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   // BlockCache implementation
340 
341   /**
342    * Cache the block with the specified name and buffer.
343    * <p>
344    * It is assumed this will NOT be called on an already cached block. In rare cases (HBASE-8547)
345    * this can happen, for which we compare the buffer contents.
346    * @param cacheKey block's cache key
347    * @param buf block buffer
348    * @param inMemory if block is in-memory
349    * @param cacheDataInL1
350    */
351   @Override
352   public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory,
353       final boolean cacheDataInL1) {
354 
355     if (buf.heapSize() > maxBlockSize) {
356       // If there are a lot of blocks that are too
357       // big this can make the logs way too noisy.
358       // So we log 2%
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       // compare the contents, if they are not equal, we are in big trouble
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    * Sanity-checking for parity between actual block cache content and metrics.
412    * Intended only for use with TRACE level logging and -ea JVM.
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    * Cache the block with the specified name and buffer.
440    * <p>
441    * @param cacheKey block's cache key
442    * @param buf block buffer
443    */
444   public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) {
445     cacheBlock(cacheKey, buf, false, false);
446   }
447 
448   /**
449    * Helper function that updates the local size counter and also updates any
450    * per-cf or per-blocktype metrics it can discern from given
451    * {@link LruCachedBlock}
452    *
453    * @param cb
454    * @param evict
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    * Get the buffer of the block with the specified name.
466    * @param cacheKey block's cache key
467    * @param caching true if the caller caches blocks on cache misses
468    * @param repeat Whether this is a repeat lookup for the same block
469    *        (used to avoid double counting cache misses when doing double-check locking)
470    * @param updateCacheMetrics Whether to update cache metrics or not
471    * @return buffer of specified cache key, or null if not in cache
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       // If there is another block cache then try and read there.
482       // However if this is a retry ( second time in double checked locking )
483       // And it's already a miss then the l2 will also be a miss.
484       if (victimHandler != null && !repeat) {
485         Cacheable result = victimHandler.getBlock(cacheKey, caching, repeat, updateCacheMetrics);
486 
487         // Promote this to L1.
488         if (result != null && caching) {
489           cacheBlock(cacheKey, result, /* inMemory = */ false, /* cacheData = */ true);
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    * Whether the cache contains block with specified cacheKey
502    * @param cacheKey
503    * @return true if contains the block
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    * Evicts all blocks for a specific HFile. This is an
519    * expensive operation implemented as a linear-time search through all blocks
520    * in the cache. Ideally this should be a search in a log-access-time map.
521    *
522    * <p>
523    * This is used for evict-on-close to remove all blocks of a specific HFile.
524    *
525    * @return the number of blocks evicted
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    * Evict the block, and it will be cached by the victim handler if exists &amp;&amp;
544    * block may be read again later
545    * @param block
546    * @param evictedByEvictionProcess true if the given block is evicted by
547    *          EvictionThread
548    * @return the heap size of evicted block
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    * Multi-threaded call to run the eviction process.
574    */
575   private void runEviction() {
576     if(evictionThread == null) {
577       evict();
578     } else {
579       evictionThread.evict();
580     }
581   }
582 
583   /**
584    * Eviction method.
585    */
586   void evict() {
587 
588     // Ensure only one eviction at a time
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       // Instantiate priority buckets
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       // Scan entire map putting into appropriate buckets
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           // this means we need to evict blocks in memory bucket to make room,
636           // so the single and multi buckets will be emptied
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           // this means no need to evict block in memory bucket,
650           // and we try best to make the ratio between single-bucket and
651           // multi-bucket is 1:2
652           long bytesRemain = s + m - bytesToFree;
653           if (3 * s <= bytesRemain) {
654             // single-bucket is small enough that no eviction happens for it
655             // hence all eviction goes from multi-bucket
656             bytesFreed = bucketMulti.free(bytesToFree);
657           } else if (3 * m <= 2 * bytesRemain) {
658             // multi-bucket is small enough that no eviction happens for it
659             // hence all eviction goes from single-bucket
660             bytesFreed = bucketSingle.free(bytesToFree);
661           } else {
662             // both buckets need to evict some blocks
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    * Used to group blocks into priority buckets.  There will be a BlockBucket
728    * for each priority (single, multi, memory).  Once bucketed, the eviction
729    * algorithm takes the appropriate number of elements out of each according
730    * to configuration parameters and their relatives sizes.
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    * Get the maximum size of this cache.
806    * @return max size in bytes
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    * Eviction thread.  Sits in waiting state until an eviction is triggered
838    * when the cache size grows above the acceptable level.<p>
839    *
840    * Thread is triggered into action by {@link LruBlockCache#runEviction()}
841    */
842   static class EvictionThread extends HasThread {
843     private WeakReference<LruBlockCache> cache;
844     private volatile boolean go = true;
845     // flag set after enter the run method, used for test
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/*Don't wait for ever*/);
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      * Used for the test.
887      */
888     boolean isEnteringRun() {
889       return this.enteringRun;
890     }
891   }
892 
893   /*
894    * Statistics thread.  Periodically prints the cache statistics to the log.
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     // Log size
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    * Get counter statistics for this cache.
934    *
935    * <p>Includes: total accesses, hits, misses, evicted blocks, and runs
936    * of the eviction processes.
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     // FindBugs ICAST_INTEGER_MULTIPLY_CAST_TO_LONG
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   // Simple calculators of sizes given factors and maxSize
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   /** Clears the cache. Used in tests. */
1090   @VisibleForTesting
1091   public void clearCache() {
1092     this.map.clear();
1093     this.elements.set(0);
1094   }
1095 
1096   /**
1097    * Used in testing. May be very inefficient.
1098    * @return the set of cached file names
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 }