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 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   * A block cache implementation that is memory-aware using {@link HeapSize},
54   * memory-bound using an LRU eviction algorithm, and concurrent: backed by a
55   * {@link ConcurrentHashMap} and with a non-blocking eviction thread giving
56   * constant-time {@link #cacheBlock} and {@link #getBlock} operations.<p>
57   *
58   * Contains three levels of block priority to allow for
59   * scan-resistance and in-memory families 
60   * {@link org.apache.hadoop.hbase.HColumnDescriptor#setInMemory(boolean)} (An
61   * in-memory column family is a column family that should be served from memory if possible):
62   * single-access, multiple-accesses, and in-memory priority.
63   * A block is added with an in-memory priority flag if
64   * {@link org.apache.hadoop.hbase.HColumnDescriptor#isInMemory()}, 
65   * otherwise a block becomes a single access
66   * priority the first time it is read into this block cache.  If a block is accessed again while
67   * in cache, it is marked as a multiple access priority block.  This delineation of blocks is used
68   * to prevent scans from thrashing the cache adding a least-frequently-used
69   * element to the eviction algorithm.<p>
70   *
71   * Each priority is given its own chunk of the total cache to ensure
72   * fairness during eviction.  Each priority will retain close to its maximum
73   * size, however, if any priority is not using its entire chunk the others
74   * are able to grow beyond their chunk size.<p>
75   *
76   * Instantiated at a minimum with the total size and average block size.
77   * All sizes are in bytes.  The block size is not especially important as this
78   * cache is fully dynamic in its sizing of blocks.  It is only used for
79   * pre-allocating data structures and in initial heap estimation of the map.<p>
80   *
81   * The detailed constructor defines the sizes for the three priorities (they
82   * should total to the <code>maximum size</code> defined).  It also sets the levels that
83   * trigger and control the eviction thread.<p>
84   *
85   * The <code>acceptable size</code> is the cache size level which triggers the eviction
86   * process to start.  It evicts enough blocks to get the size below the
87   * minimum size specified.<p>
88   *
89   * Eviction happens in a separate thread and involves a single full-scan
90   * of the map.  It determines how many bytes must be freed to reach the minimum
91   * size, and then while scanning determines the fewest least-recently-used
92   * blocks necessary from each of the three priorities (would be 3 times bytes
93   * to free).  It then uses the priority chunk sizes to evict fairly according
94   * to the relative sizes and usage.
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    * Percentage of total size that eviction will evict until; e.g. if set to .8, then we will keep
103    * evicting during an eviction run till the cache size is down to 80% of the total.
104    */
105   static final String LRU_MIN_FACTOR_CONFIG_NAME = "hbase.lru.blockcache.min.factor";
106 
107   /**
108    * Acceptable size of cache (no evictions if size < acceptable)
109    */
110   static final String LRU_ACCEPTABLE_FACTOR_CONFIG_NAME = "hbase.lru.blockcache.acceptable.factor";
111 
112   /**
113    * Hard capacity limit of cache, will reject any put if size > this * acceptable
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    * Configuration key to force data-block always (except in-memory are too much)
122    * cached in memory for in-memory hfile, unlike inMemory, which is a column-family
123    * configuration, inMemoryForceMode is a cluster-wide configuration
124    */
125   static final String LRU_IN_MEMORY_FORCE_MODE_CONFIG_NAME = "hbase.lru.rs.inmemoryforcemode";
126 
127   /** Default Configuration Parameters*/
128 
129   /** Backing Concurrent Map Configuration */
130   static final float DEFAULT_LOAD_FACTOR = 0.75f;
131   static final int DEFAULT_CONCURRENCY_LEVEL = 16;
132 
133   /** Eviction thresholds */
134   static final float DEFAULT_MIN_FACTOR = 0.95f;
135   static final float DEFAULT_ACCEPTABLE_FACTOR = 0.99f;
136 
137   /** Priority buckets */
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   /** default hard capacity limit */
143   static final float DEFAULT_HARD_CAPACITY_LIMIT_FACTOR = 1.2f;
144 
145   static final boolean DEFAULT_IN_MEMORY_FORCE_MODE = false;
146 
147   /** Statistics thread */
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   /** Concurrent map (the cache) */
153   private transient final Map<BlockCacheKey,LruCachedBlock> map;
154 
155   /** Eviction lock (locked when eviction in process) */
156   private transient final ReentrantLock evictionLock = new ReentrantLock(true);
157   private final long maxBlockSize;
158 
159   /** Volatile boolean to track if we are in an eviction process or not */
160   private volatile boolean evictionInProgress = false;
161 
162   /** Eviction thread */
163   private transient final EvictionThread evictionThread;
164 
165   /** Statistics thread schedule pool (for heavy debugging, could remove) */
166   private transient final ScheduledExecutorService scheduleThreadPool =
167     Executors.newScheduledThreadPool(1,
168       new ThreadFactoryBuilder().setNameFormat("LruBlockCacheStatsExecutor")
169         .setDaemon(true).build());
170 
171   /** Current size of cache */
172   private final AtomicLong size;
173 
174   /** Current size of data blocks */
175   private final AtomicLong dataBlockSize;
176 
177   /** Current number of cached elements */
178   private final AtomicLong elements;
179 
180   /** Current number of cached data block elements */
181   private final AtomicLong dataBlockElements;
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.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(); // FindBugs SC_START_IN_CTOR
324     } else {
325       this.evictionThread = null;
326     }
327     // TODO: Add means of turning this off.  Bit obnoxious running thread just to make a log
328     // every five minutes.
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   // BlockCache implementation
342 
343   /**
344    * Cache the block with the specified name and buffer.
345    * <p>
346    * It is assumed this will NOT be called on an already cached block. In rare cases (HBASE-8547)
347    * this can happen, for which we compare the buffer contents.
348    * @param cacheKey block's cache key
349    * @param buf block buffer
350    * @param inMemory if block is in-memory
351    * @param cacheDataInL1
352    */
353   @Override
354   public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory,
355       final boolean cacheDataInL1) {
356 
357     if (buf.heapSize() > maxBlockSize) {
358       // If there are a lot of blocks that are too
359       // big this can make the logs way too noisy.
360       // So we log 2%
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    * Sanity-checking for parity between actual block cache content and metrics.
410    * Intended only for use with TRACE level logging and -ea JVM.
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    * Cache the block with the specified name and buffer.
429    * <p>
430    * @param cacheKey block's cache key
431    * @param buf block buffer
432    */
433   @Override
434   public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) {
435     cacheBlock(cacheKey, buf, false, false);
436   }
437 
438   /**
439    * Helper function that updates the local size counter and also updates any
440    * per-cf or per-blocktype metrics it can discern from given
441    * {@link LruCachedBlock}
442    *
443    * @param cb
444    * @param evict
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    * Get the buffer of the block with the specified name.
460    * @param cacheKey block's cache key
461    * @param caching true if the caller caches blocks on cache misses
462    * @param repeat Whether this is a repeat lookup for the same block
463    *        (used to avoid double counting cache misses when doing double-check locking)
464    * @param updateCacheMetrics Whether to update cache metrics or not
465    * @return buffer of specified cache key, or null if not in cache
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       // If there is another block cache then try and read there.
476       // However if this is a retry ( second time in double checked locking )
477       // And it's already a miss then the l2 will also be a miss.
478       if (victimHandler != null && !repeat) {
479         Cacheable result = victimHandler.getBlock(cacheKey, caching, repeat, updateCacheMetrics);
480 
481         // Promote this to L1.
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    * Whether the cache contains block with specified cacheKey
496    * @param cacheKey
497    * @return true if contains the block
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    * Evicts all blocks for a specific HFile. This is an
512    * expensive operation implemented as a linear-time search through all blocks
513    * in the cache. Ideally this should be a search in a log-access-time map.
514    *
515    * <p>
516    * This is used for evict-on-close to remove all blocks of a specific HFile.
517    *
518    * @return the number of blocks evicted
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    * Evict the block, and it will be cached by the victim handler if exists &amp;&amp;
537    * block may be read again later
538    * @param block
539    * @param evictedByEvictionProcess true if the given block is evicted by
540    *          EvictionThread
541    * @return the heap size of evicted block
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    * Multi-threaded call to run the eviction process.
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    * Eviction method.
594    */
595   void evict() {
596 
597     // Ensure only one eviction at a time
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       // Instantiate priority buckets
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       // Scan entire map putting into appropriate buckets
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           // this means we need to evict blocks in memory bucket to make room,
645           // so the single and multi buckets will be emptied
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           // this means no need to evict block in memory bucket,
659           // and we try best to make the ratio between single-bucket and
660           // multi-bucket is 1:2
661           long bytesRemain = s + m - bytesToFree;
662           if (3 * s <= bytesRemain) {
663             // single-bucket is small enough that no eviction happens for it
664             // hence all eviction goes from multi-bucket
665             bytesFreed = bucketMulti.free(bytesToFree);
666           } else if (3 * m <= 2 * bytesRemain) {
667             // multi-bucket is small enough that no eviction happens for it
668             // hence all eviction goes from single-bucket
669             bytesFreed = bucketSingle.free(bytesToFree);
670           } else {
671             // both buckets need to evict some blocks
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    * Used to group blocks into priority buckets.  There will be a BlockBucket
736    * for each priority (single, multi, memory).  Once bucketed, the eviction
737    * algorithm takes the appropriate number of elements out of each according
738    * to configuration parameters and their relatives sizes.
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    * Get the maximum size of this cache.
815    * @return max size in bytes
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    * Eviction thread.  Sits in waiting state until an eviction is triggered
859    * when the cache size grows above the acceptable level.<p>
860    *
861    * Thread is triggered into action by {@link LruBlockCache#runEviction()}
862    */
863   static class EvictionThread extends HasThread {
864     private WeakReference<LruBlockCache> cache;
865     private volatile boolean go = true;
866     // flag set after enter the run method, used for test
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/*Don't wait for ever*/);
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      * Used for the test.
908      */
909     boolean isEnteringRun() {
910       return this.enteringRun;
911     }
912   }
913 
914   /*
915    * Statistics thread.  Periodically prints the cache statistics to the log.
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     // Log size
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    * Get counter statistics for this cache.
955    *
956    * <p>Includes: total accesses, hits, misses, evicted blocks, and runs
957    * of the eviction processes.
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     // FindBugs ICAST_INTEGER_MULTIPLY_CAST_TO_LONG
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   // Simple calculators of sizes given factors and maxSize
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   /** Clears the cache. Used in tests. */
1117   @VisibleForTesting
1118   public void clearCache() {
1119     this.map.clear();
1120     this.elements.set(0);
1121   }
1122 
1123   /**
1124    * Used in testing. May be very inefficient.
1125    * @return the set of cached file names
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 }