View Javadoc

1   /**
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15  
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   */
21  package org.apache.hadoop.hbase.io.hfile.bucket;
22  
23  import java.io.File;
24  import java.io.FileInputStream;
25  import java.io.FileNotFoundException;
26  import java.io.FileOutputStream;
27  import java.io.IOException;
28  import java.io.ObjectInputStream;
29  import java.io.ObjectOutputStream;
30  import java.io.Serializable;
31  import java.nio.ByteBuffer;
32  import java.util.ArrayList;
33  import java.util.Comparator;
34  import java.util.HashSet;
35  import java.util.Iterator;
36  import java.util.List;
37  import java.util.Map;
38  import java.util.NavigableSet;
39  import java.util.PriorityQueue;
40  import java.util.Set;
41  import java.util.concurrent.ArrayBlockingQueue;
42  import java.util.concurrent.BlockingQueue;
43  import java.util.concurrent.ConcurrentHashMap;
44  import java.util.concurrent.ConcurrentMap;
45  import java.util.concurrent.ConcurrentSkipListSet;
46  import java.util.concurrent.Executors;
47  import java.util.concurrent.ScheduledExecutorService;
48  import java.util.concurrent.TimeUnit;
49  import java.util.concurrent.atomic.AtomicLong;
50  import java.util.concurrent.locks.Lock;
51  import java.util.concurrent.locks.ReentrantLock;
52  import java.util.concurrent.locks.ReentrantReadWriteLock;
53  
54  import org.apache.commons.logging.Log;
55  import org.apache.commons.logging.LogFactory;
56  import org.apache.hadoop.hbase.classification.InterfaceAudience;
57  import org.apache.hadoop.hbase.io.HeapSize;
58  import org.apache.hadoop.hbase.io.hfile.BlockCache;
59  import org.apache.hadoop.hbase.io.hfile.BlockCacheKey;
60  import org.apache.hadoop.hbase.io.hfile.BlockCacheUtil;
61  import org.apache.hadoop.hbase.io.hfile.BlockPriority;
62  import org.apache.hadoop.hbase.io.hfile.BlockType;
63  import org.apache.hadoop.hbase.io.hfile.CacheStats;
64  import org.apache.hadoop.hbase.io.hfile.Cacheable;
65  import org.apache.hadoop.hbase.io.hfile.CacheableDeserializer;
66  import org.apache.hadoop.hbase.io.hfile.CacheableDeserializerIdManager;
67  import org.apache.hadoop.hbase.io.hfile.CachedBlock;
68  import org.apache.hadoop.hbase.io.hfile.HFileBlock;
69  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
70  import org.apache.hadoop.hbase.util.HasThread;
71  import org.apache.hadoop.hbase.util.IdReadWriteLock;
72  import org.apache.hadoop.util.StringUtils;
73  
74  import com.google.common.annotations.VisibleForTesting;
75  import com.google.common.util.concurrent.ThreadFactoryBuilder;
76  
77  /**
78   * BucketCache uses {@link BucketAllocator} to allocate/free blocks, and uses
79   * BucketCache#ramCache and BucketCache#backingMap in order to
80   * determine if a given element is in the cache. The bucket cache can use on-heap or
81   * off-heap memory {@link ByteBufferIOEngine} or in a file {@link FileIOEngine} to
82   * store/read the block data.
83   *
84   * <p>Eviction is via a similar algorithm as used in
85   * {@link org.apache.hadoop.hbase.io.hfile.LruBlockCache}
86   *
87   * <p>BucketCache can be used as mainly a block cache (see
88   * {@link org.apache.hadoop.hbase.io.hfile.CombinedBlockCache}), combined with
89   * combined with LruBlockCache to decrease CMS GC and heap fragmentation.
90   *
91   * <p>It also can be used as a secondary cache (e.g. using a file on ssd/fusionio to store
92   * blocks) to enlarge cache space via
93   * {@link org.apache.hadoop.hbase.io.hfile.LruBlockCache#setVictimCache}
94   */
95  @InterfaceAudience.Private
96  public class BucketCache implements BlockCache, HeapSize {
97    private static final Log LOG = LogFactory.getLog(BucketCache.class);
98  
99    /** Priority buckets */
100   private static final float DEFAULT_SINGLE_FACTOR = 0.25f;
101   private static final float DEFAULT_MULTI_FACTOR = 0.50f;
102   private static final float DEFAULT_MEMORY_FACTOR = 0.25f;
103   private static final float DEFAULT_EXTRA_FREE_FACTOR = 0.10f;
104 
105   private static final float DEFAULT_ACCEPT_FACTOR = 0.95f;
106   private static final float DEFAULT_MIN_FACTOR = 0.85f;
107 
108   // Number of blocks to clear for each of the bucket size that is full
109   private static final int DEFAULT_FREE_ENTIRE_BLOCK_FACTOR = 2;
110 
111   /** Statistics thread */
112   private static final int statThreadPeriod = 5 * 60;
113 
114   final static int DEFAULT_WRITER_THREADS = 3;
115   final static int DEFAULT_WRITER_QUEUE_ITEMS = 64;
116 
117   // Store/read block data
118   transient final IOEngine ioEngine;
119 
120   // Store the block in this map before writing it to cache
121   @VisibleForTesting
122   transient final ConcurrentMap<BlockCacheKey, RAMQueueEntry> ramCache;
123   // In this map, store the block's meta data like offset, length
124   @VisibleForTesting
125   transient ConcurrentMap<BlockCacheKey, BucketEntry> backingMap;
126 
127   /**
128    * Flag if the cache is enabled or not... We shut it off if there are IO
129    * errors for some time, so that Bucket IO exceptions/errors don't bring down
130    * the HBase server.
131    */
132   private volatile boolean cacheEnabled;
133 
134   /**
135    * A list of writer queues.  We have a queue per {@link WriterThread} we have running.
136    * In other words, the work adding blocks to the BucketCache is divided up amongst the
137    * running WriterThreads.  Its done by taking hash of the cache key modulo queue count.
138    * WriterThread when it runs takes whatever has been recently added and 'drains' the entries
139    * to the BucketCache.  It then updates the ramCache and backingMap accordingly.
140    */
141   @VisibleForTesting
142   transient final ArrayList<BlockingQueue<RAMQueueEntry>> writerQueues =
143       new ArrayList<BlockingQueue<RAMQueueEntry>>();
144   @VisibleForTesting
145   transient final WriterThread[] writerThreads;
146 
147   /** Volatile boolean to track if free space is in process or not */
148   private volatile boolean freeInProgress = false;
149   private transient final Lock freeSpaceLock = new ReentrantLock();
150 
151   private UniqueIndexMap<Integer> deserialiserMap = new UniqueIndexMap<Integer>();
152 
153   private final AtomicLong realCacheSize = new AtomicLong(0);
154   private final AtomicLong heapSize = new AtomicLong(0);
155   /** Current number of cached elements */
156   private final AtomicLong blockNumber = new AtomicLong(0);
157 
158   /** Cache access count (sequential ID) */
159   private final AtomicLong accessCount = new AtomicLong(0);
160 
161   private static final int DEFAULT_CACHE_WAIT_TIME = 50;
162   // Used in test now. If the flag is false and the cache speed is very fast,
163   // bucket cache will skip some blocks when caching. If the flag is true, we
164   // will wait blocks flushed to IOEngine for some time when caching
165   boolean wait_when_cache = false;
166 
167   private final BucketCacheStats cacheStats = new BucketCacheStats();
168 
169   private final String persistencePath;
170   private final long cacheCapacity;
171   /** Approximate block size */
172   private final long blockSize;
173 
174   /** Duration of IO errors tolerated before we disable cache, 1 min as default */
175   private final int ioErrorsTolerationDuration;
176   // 1 min
177   public static final int DEFAULT_ERROR_TOLERATION_DURATION = 60 * 1000;
178 
179   // Start time of first IO error when reading or writing IO Engine, it will be
180   // reset after a successful read/write.
181   private volatile long ioErrorStartTime = -1;
182 
183   /**
184    * A ReentrantReadWriteLock to lock on a particular block identified by offset.
185    * The purpose of this is to avoid freeing the block which is being read.
186    */
187   @VisibleForTesting
188   transient final IdReadWriteLock offsetLock = new IdReadWriteLock();
189 
190   private final NavigableSet<BlockCacheKey> blocksByHFile =
191       new ConcurrentSkipListSet<BlockCacheKey>(new Comparator<BlockCacheKey>() {
192         @Override
193         public int compare(BlockCacheKey a, BlockCacheKey b) {
194           int nameComparison = a.getHfileName().compareTo(b.getHfileName());
195           if (nameComparison != 0) {
196             return nameComparison;
197           }
198 
199           if (a.getOffset() == b.getOffset()) {
200             return 0;
201           } else if (a.getOffset() < b.getOffset()) {
202             return -1;
203           }
204           return 1;
205         }
206       });
207 
208   /** Statistics thread schedule pool (for heavy debugging, could remove) */
209   private transient final ScheduledExecutorService scheduleThreadPool =
210     Executors.newScheduledThreadPool(1,
211       new ThreadFactoryBuilder().setNameFormat("BucketCacheStatsExecutor").setDaemon(true).build());
212 
213   // Allocate or free space for the block
214   private transient BucketAllocator bucketAllocator;
215 
216   public BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
217       int writerThreadNum, int writerQLen, String persistencePath) throws FileNotFoundException,
218       IOException {
219     this(ioEngineName, capacity, blockSize, bucketSizes, writerThreadNum, writerQLen,
220       persistencePath, DEFAULT_ERROR_TOLERATION_DURATION);
221   }
222 
223   public BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
224       int writerThreadNum, int writerQLen, String persistencePath, int ioErrorsTolerationDuration)
225       throws FileNotFoundException, IOException {
226     this.ioEngine = getIOEngineFromName(ioEngineName, capacity);
227     this.writerThreads = new WriterThread[writerThreadNum];
228     long blockNumCapacity = capacity / blockSize;
229     if (blockNumCapacity >= Integer.MAX_VALUE) {
230       // Enough for about 32TB of cache!
231       throw new IllegalArgumentException("Cache capacity is too large, only support 32TB now");
232     }
233 
234     this.cacheCapacity = capacity;
235     this.persistencePath = persistencePath;
236     this.blockSize = blockSize;
237     this.ioErrorsTolerationDuration = ioErrorsTolerationDuration;
238 
239     bucketAllocator = new BucketAllocator(capacity, bucketSizes);
240     for (int i = 0; i < writerThreads.length; ++i) {
241       writerQueues.add(new ArrayBlockingQueue<RAMQueueEntry>(writerQLen));
242     }
243 
244     assert writerQueues.size() == writerThreads.length;
245     this.ramCache = new ConcurrentHashMap<BlockCacheKey, RAMQueueEntry>();
246 
247     this.backingMap = new ConcurrentHashMap<BlockCacheKey, BucketEntry>((int) blockNumCapacity);
248 
249     if (ioEngine.isPersistent() && persistencePath != null) {
250       try {
251         retrieveFromFile(bucketSizes);
252       } catch (IOException ioex) {
253         LOG.error("Can't restore from file because of", ioex);
254       } catch (ClassNotFoundException cnfe) {
255         LOG.error("Can't restore from file in rebuild because can't deserialise",cnfe);
256         throw new RuntimeException(cnfe);
257       }
258     }
259     final String threadName = Thread.currentThread().getName();
260     this.cacheEnabled = true;
261     for (int i = 0; i < writerThreads.length; ++i) {
262       writerThreads[i] = new WriterThread(writerQueues.get(i));
263       writerThreads[i].setName(threadName + "-BucketCacheWriter-" + i);
264       writerThreads[i].setDaemon(true);
265     }
266     startWriterThreads();
267 
268     // Run the statistics thread periodically to print the cache statistics log
269     // TODO: Add means of turning this off.  Bit obnoxious running thread just to make a log
270     // every five minutes.
271     this.scheduleThreadPool.scheduleAtFixedRate(new StatisticsThread(this),
272         statThreadPeriod, statThreadPeriod, TimeUnit.SECONDS);
273     LOG.info("Started bucket cache; ioengine=" + ioEngineName +
274         ", capacity=" + StringUtils.byteDesc(capacity) +
275       ", blockSize=" + StringUtils.byteDesc(blockSize) + ", writerThreadNum=" +
276         writerThreadNum + ", writerQLen=" + writerQLen + ", persistencePath=" +
277       persistencePath + ", bucketAllocator=" + this.bucketAllocator.getClass().getName());
278   }
279 
280   /**
281    * Called by the constructor to start the writer threads. Used by tests that need to override
282    * starting the threads.
283    */
284   @VisibleForTesting
285   protected void startWriterThreads() {
286     for (WriterThread thread : writerThreads) {
287       thread.start();
288     }
289   }
290 
291   @VisibleForTesting
292   boolean isCacheEnabled() {
293     return this.cacheEnabled;
294   }
295 
296   public long getMaxSize() {
297     return this.cacheCapacity;
298   }
299 
300   public String getIoEngine() {
301     return ioEngine.toString();
302   }
303 
304   /**
305    * Get the IOEngine from the IO engine name
306    * @param ioEngineName
307    * @param capacity
308    * @return the IOEngine
309    * @throws IOException
310    */
311   private IOEngine getIOEngineFromName(String ioEngineName, long capacity)
312       throws IOException {
313     if (ioEngineName.startsWith("file:") || ioEngineName.startsWith("files:")) {
314       // In order to make the usage simple, we only need the prefix 'files:' in
315       // document whether one or multiple file(s), but also support 'file:' for
316       // the compatibility
317       String[] filePaths =
318           ioEngineName.substring(ioEngineName.indexOf(":") + 1).split(FileIOEngine.FILE_DELIMITER);
319       return new FileIOEngine(capacity, filePaths);
320     } else if (ioEngineName.startsWith("offheap"))
321       return new ByteBufferIOEngine(capacity, true);
322     else if (ioEngineName.startsWith("heap"))
323       return new ByteBufferIOEngine(capacity, false);
324     else
325       throw new IllegalArgumentException(
326           "Don't understand io engine name for cache - prefix with file:, heap or offheap");
327   }
328 
329   /**
330    * Cache the block with the specified name and buffer.
331    * @param cacheKey block's cache key
332    * @param buf block buffer
333    */
334   @Override
335   public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) {
336     cacheBlock(cacheKey, buf, false, false);
337   }
338 
339   /**
340    * Cache the block with the specified name and buffer.
341    * @param cacheKey block's cache key
342    * @param cachedItem block buffer
343    * @param inMemory if block is in-memory
344    * @param cacheDataInL1
345    */
346   @Override
347   public void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory,
348       final boolean cacheDataInL1) {
349     cacheBlockWithWait(cacheKey, cachedItem, inMemory, wait_when_cache);
350   }
351 
352   /**
353    * Cache the block to ramCache
354    * @param cacheKey block's cache key
355    * @param cachedItem block buffer
356    * @param inMemory if block is in-memory
357    * @param wait if true, blocking wait when queue is full
358    */
359   public void cacheBlockWithWait(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory,
360       boolean wait) {
361     if (LOG.isTraceEnabled()) LOG.trace("Caching key=" + cacheKey + ", item=" + cachedItem);
362     if (!cacheEnabled) {
363       return;
364     }
365 
366     if (backingMap.containsKey(cacheKey)) {
367       return;
368     }
369 
370     /*
371      * Stuff the entry into the RAM cache so it can get drained to the persistent store
372      */
373     RAMQueueEntry re =
374         new RAMQueueEntry(cacheKey, cachedItem, accessCount.incrementAndGet(), inMemory);
375     if (ramCache.putIfAbsent(cacheKey, re) != null) {
376       return;
377     }
378     int queueNum = (cacheKey.hashCode() & 0x7FFFFFFF) % writerQueues.size();
379     BlockingQueue<RAMQueueEntry> bq = writerQueues.get(queueNum);
380     boolean successfulAddition = false;
381     if (wait) {
382       try {
383         successfulAddition = bq.offer(re, DEFAULT_CACHE_WAIT_TIME, TimeUnit.MILLISECONDS);
384       } catch (InterruptedException e) {
385         Thread.currentThread().interrupt();
386       }
387     } else {
388       successfulAddition = bq.offer(re);
389     }
390     if (!successfulAddition) {
391       ramCache.remove(cacheKey);
392       cacheStats.failInsert();
393     } else {
394       this.blockNumber.incrementAndGet();
395       this.heapSize.addAndGet(cachedItem.heapSize());
396       blocksByHFile.add(cacheKey);
397     }
398   }
399 
400   /**
401    * Get the buffer of the block with the specified key.
402    * @param key block's cache key
403    * @param caching true if the caller caches blocks on cache misses
404    * @param repeat Whether this is a repeat lookup for the same block
405    * @param updateCacheMetrics Whether we should update cache metrics or not
406    * @return buffer of specified cache key, or null if not in cache
407    */
408   @Override
409   public Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat,
410       boolean updateCacheMetrics) {
411     if (!cacheEnabled) {
412       return null;
413     }
414     RAMQueueEntry re = ramCache.get(key);
415     if (re != null) {
416       if (updateCacheMetrics) {
417         cacheStats.hit(caching, key.isPrimary(), key.getBlockType());
418       }
419       re.access(accessCount.incrementAndGet());
420       return re.getData();
421     }
422     BucketEntry bucketEntry = backingMap.get(key);
423     if (bucketEntry != null) {
424       long start = System.nanoTime();
425       ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntry.offset());
426       try {
427         lock.readLock().lock();
428         // We can not read here even if backingMap does contain the given key because its offset
429         // maybe changed. If we lock BlockCacheKey instead of offset, then we can only check
430         // existence here.
431         if (bucketEntry.equals(backingMap.get(key))) {
432           int len = bucketEntry.getLength();
433           if (LOG.isTraceEnabled()) {
434             LOG.trace("Read offset=" + bucketEntry.offset() + ", len=" + len);
435           }
436           ByteBuffer bb = ByteBuffer.allocate(len);
437           int lenRead = ioEngine.read(bb, bucketEntry.offset());
438           if (lenRead != len) {
439             throw new RuntimeException("Only " + lenRead + " bytes read, " + len + " expected");
440           }
441           CacheableDeserializer<Cacheable> deserializer =
442             bucketEntry.deserializerReference(this.deserialiserMap);
443           Cacheable cachedBlock = deserializer.deserialize(bb, true);
444           long timeTaken = System.nanoTime() - start;
445           if (updateCacheMetrics) {
446             cacheStats.hit(caching, key.isPrimary(), key.getBlockType());
447             cacheStats.ioHit(timeTaken);
448           }
449           bucketEntry.access(accessCount.incrementAndGet());
450           if (this.ioErrorStartTime > 0) {
451             ioErrorStartTime = -1;
452           }
453           return cachedBlock;
454         }
455       } catch (IOException ioex) {
456         LOG.error("Failed reading block " + key + " from bucket cache", ioex);
457         checkIOErrorIsTolerated();
458       } finally {
459         lock.readLock().unlock();
460       }
461     }
462     if (!repeat && updateCacheMetrics) {
463       cacheStats.miss(caching, key.isPrimary(), key.getBlockType());
464     }
465     return null;
466   }
467 
468   @VisibleForTesting
469   void blockEvicted(BlockCacheKey cacheKey, BucketEntry bucketEntry, boolean decrementBlockNumber) {
470     bucketAllocator.freeBlock(bucketEntry.offset());
471     realCacheSize.addAndGet(-1 * bucketEntry.getLength());
472     blocksByHFile.remove(cacheKey);
473     if (decrementBlockNumber) {
474       this.blockNumber.decrementAndGet();
475     }
476   }
477 
478   @Override
479   public boolean evictBlock(BlockCacheKey cacheKey) {
480     if (!cacheEnabled) {
481       return false;
482     }
483     RAMQueueEntry removedBlock = ramCache.remove(cacheKey);
484     if (removedBlock != null) {
485       this.blockNumber.decrementAndGet();
486       this.heapSize.addAndGet(-1 * removedBlock.getData().heapSize());
487     }
488     BucketEntry bucketEntry = backingMap.get(cacheKey);
489     if (bucketEntry == null) {
490       if (removedBlock != null) {
491         cacheStats.evicted(0, cacheKey.isPrimary());
492         return true;
493       } else {
494         return false;
495       }
496     }
497     ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntry.offset());
498     try {
499       lock.writeLock().lock();
500       if (backingMap.remove(cacheKey, bucketEntry)) {
501         blockEvicted(cacheKey, bucketEntry, removedBlock == null);
502       } else {
503         return false;
504       }
505     } finally {
506       lock.writeLock().unlock();
507     }
508     cacheStats.evicted(bucketEntry.getCachedTime(), cacheKey.isPrimary());
509     return true;
510   }
511 
512   /*
513    * Statistics thread.  Periodically output cache statistics to the log.
514    */
515   private static class StatisticsThread extends Thread {
516     private final BucketCache bucketCache;
517 
518     public StatisticsThread(BucketCache bucketCache) {
519       super("BucketCacheStatsThread");
520       setDaemon(true);
521       this.bucketCache = bucketCache;
522     }
523 
524     @Override
525     public void run() {
526       bucketCache.logStats();
527     }
528   }
529 
530   public void logStats() {
531     long totalSize = bucketAllocator.getTotalSize();
532     long usedSize = bucketAllocator.getUsedSize();
533     long freeSize = totalSize - usedSize;
534     long cacheSize = getRealCacheSize();
535     LOG.info("failedBlockAdditions=" + cacheStats.getFailedInserts() + ", " +
536         "totalSize=" + StringUtils.byteDesc(totalSize) + ", " +
537         "freeSize=" + StringUtils.byteDesc(freeSize) + ", " +
538         "usedSize=" + StringUtils.byteDesc(usedSize) +", " +
539         "cacheSize=" + StringUtils.byteDesc(cacheSize) +", " +
540         "accesses=" + cacheStats.getRequestCount() + ", " +
541         "hits=" + cacheStats.getHitCount() + ", " +
542         "IOhitsPerSecond=" + cacheStats.getIOHitsPerSecond() + ", " +
543         "IOTimePerHit=" + String.format("%.2f", cacheStats.getIOTimePerHit())+ ", " +
544         "hitRatio=" + (cacheStats.getHitCount() == 0 ? "0," :
545           (StringUtils.formatPercent(cacheStats.getHitRatio(), 2)+ ", ")) +
546         "cachingAccesses=" + cacheStats.getRequestCachingCount() + ", " +
547         "cachingHits=" + cacheStats.getHitCachingCount() + ", " +
548         "cachingHitsRatio=" +(cacheStats.getHitCachingCount() == 0 ? "0," :
549           (StringUtils.formatPercent(cacheStats.getHitCachingRatio(), 2)+ ", ")) +
550         "evictions=" + cacheStats.getEvictionCount() + ", " +
551         "evicted=" + cacheStats.getEvictedCount() + ", " +
552         "evictedPerRun=" + cacheStats.evictedPerEviction());
553     cacheStats.reset();
554   }
555 
556   public long getRealCacheSize() {
557     return this.realCacheSize.get();
558   }
559 
560   private long acceptableSize() {
561     return (long) Math.floor(bucketAllocator.getTotalSize() * DEFAULT_ACCEPT_FACTOR);
562   }
563 
564   private long singleSize() {
565     return (long) Math.floor(bucketAllocator.getTotalSize()
566         * DEFAULT_SINGLE_FACTOR * DEFAULT_MIN_FACTOR);
567   }
568 
569   private long multiSize() {
570     return (long) Math.floor(bucketAllocator.getTotalSize() * DEFAULT_MULTI_FACTOR
571         * DEFAULT_MIN_FACTOR);
572   }
573 
574   private long memorySize() {
575     return (long) Math.floor(bucketAllocator.getTotalSize() * DEFAULT_MEMORY_FACTOR
576         * DEFAULT_MIN_FACTOR);
577   }
578 
579   /**
580    * Return the count of bucketSizeinfos still needf ree space
581    */
582   private int bucketSizesAboveThresholdCount(float minFactor) {
583     BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
584     int fullCount = 0;
585     for (int i = 0; i < stats.length; i++) {
586       long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - minFactor));
587       freeGoal = Math.max(freeGoal, 1);
588       if (stats[i].freeCount() < freeGoal) {
589         fullCount++;
590       }
591     }
592     return fullCount;
593   }
594 
595   /**
596    * This method will find the buckets that are minimally occupied
597    * and are not reference counted and will free them completely
598    * without any constraint on the access times of the elements,
599    * and as a process will completely free at most the number of buckets
600    * passed, sometimes it might not due to changing refCounts
601    *
602    * @param completelyFreeBucketsNeeded number of buckets to free
603    **/
604   private void freeEntireBuckets(int completelyFreeBucketsNeeded) {
605     if (completelyFreeBucketsNeeded != 0) {
606       // First we will build a set where the offsets are reference counted, usually
607       // this set is small around O(Handler Count) unless something else is wrong
608       Set<Integer> inUseBuckets = new HashSet<Integer>();
609       for (BucketEntry entry : backingMap.values()) {
610         inUseBuckets.add(bucketAllocator.getBucketIndex(entry.offset()));
611       }
612 
613       Set<Integer> candidateBuckets = bucketAllocator.getLeastFilledBuckets(
614           inUseBuckets, completelyFreeBucketsNeeded);
615       for (Map.Entry<BlockCacheKey, BucketEntry> entry : backingMap.entrySet()) {
616         if (candidateBuckets.contains(bucketAllocator
617             .getBucketIndex(entry.getValue().offset()))) {
618           evictBlock(entry.getKey());
619         }
620       }
621     }
622   }
623 
624   /**
625    * Free the space if the used size reaches acceptableSize() or one size block
626    * couldn't be allocated. When freeing the space, we use the LRU algorithm and
627    * ensure there must be some blocks evicted
628    * @param why Why we are being called
629    */
630   private void freeSpace(final String why) {
631     // Ensure only one freeSpace progress at a time
632     if (!freeSpaceLock.tryLock()) {
633       return;
634     }
635     try {
636       freeInProgress = true;
637       long bytesToFreeWithoutExtra = 0;
638       // Calculate free byte for each bucketSizeinfo
639       StringBuffer msgBuffer = LOG.isDebugEnabled()? new StringBuffer(): null;
640       BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
641       long[] bytesToFreeForBucket = new long[stats.length];
642       for (int i = 0; i < stats.length; i++) {
643         bytesToFreeForBucket[i] = 0;
644         long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - DEFAULT_MIN_FACTOR));
645         freeGoal = Math.max(freeGoal, 1);
646         if (stats[i].freeCount() < freeGoal) {
647           bytesToFreeForBucket[i] = stats[i].itemSize() * (freeGoal - stats[i].freeCount());
648           bytesToFreeWithoutExtra += bytesToFreeForBucket[i];
649           if (msgBuffer != null) {
650             msgBuffer.append("Free for bucketSize(" + stats[i].itemSize() + ")="
651               + StringUtils.byteDesc(bytesToFreeForBucket[i]) + ", ");
652           }
653         }
654       }
655       if (msgBuffer != null) {
656         msgBuffer.append("Free for total=" + StringUtils.byteDesc(bytesToFreeWithoutExtra) + ", ");
657       }
658 
659       if (bytesToFreeWithoutExtra <= 0) {
660         return;
661       }
662       long currentSize = bucketAllocator.getUsedSize();
663       long totalSize = bucketAllocator.getTotalSize();
664       if (LOG.isDebugEnabled() && msgBuffer != null) {
665         LOG.debug("Free started because \"" + why + "\"; " + msgBuffer.toString() +
666           " of current used=" + StringUtils.byteDesc(currentSize) + ", actual cacheSize=" +
667           StringUtils.byteDesc(realCacheSize.get()) + ", total=" + StringUtils.byteDesc(totalSize));
668       }
669 
670       long bytesToFreeWithExtra = (long) Math.floor(bytesToFreeWithoutExtra
671           * (1 + DEFAULT_EXTRA_FREE_FACTOR));
672 
673       // Instantiate priority buckets
674       BucketEntryGroup bucketSingle = new BucketEntryGroup(bytesToFreeWithExtra,
675           blockSize, singleSize());
676       BucketEntryGroup bucketMulti = new BucketEntryGroup(bytesToFreeWithExtra,
677           blockSize, multiSize());
678       BucketEntryGroup bucketMemory = new BucketEntryGroup(bytesToFreeWithExtra,
679           blockSize, memorySize());
680 
681       // Scan entire map putting bucket entry into appropriate bucket entry
682       // group
683       for (Map.Entry<BlockCacheKey, BucketEntry> bucketEntryWithKey : backingMap.entrySet()) {
684         switch (bucketEntryWithKey.getValue().getPriority()) {
685           case SINGLE: {
686             bucketSingle.add(bucketEntryWithKey);
687             break;
688           }
689           case MULTI: {
690             bucketMulti.add(bucketEntryWithKey);
691             break;
692           }
693           case MEMORY: {
694             bucketMemory.add(bucketEntryWithKey);
695             break;
696           }
697         }
698       }
699 
700       PriorityQueue<BucketEntryGroup> bucketQueue = new PriorityQueue<BucketEntryGroup>(3);
701 
702       bucketQueue.add(bucketSingle);
703       bucketQueue.add(bucketMulti);
704       bucketQueue.add(bucketMemory);
705 
706       int remainingBuckets = bucketQueue.size();
707       long bytesFreed = 0;
708 
709       BucketEntryGroup bucketGroup;
710       while ((bucketGroup = bucketQueue.poll()) != null) {
711         long overflow = bucketGroup.overflow();
712         if (overflow > 0) {
713           long bucketBytesToFree = Math.min(overflow,
714               (bytesToFreeWithoutExtra - bytesFreed) / remainingBuckets);
715           bytesFreed += bucketGroup.free(bucketBytesToFree);
716         }
717         remainingBuckets--;
718       }
719 
720       // Check and free if there are buckets that still need freeing of space
721       if (bucketSizesAboveThresholdCount(DEFAULT_MIN_FACTOR) > 0) {
722         bucketQueue.clear();
723         remainingBuckets = 3;
724 
725         bucketQueue.add(bucketSingle);
726         bucketQueue.add(bucketMulti);
727         bucketQueue.add(bucketMemory);
728 
729         while ((bucketGroup = bucketQueue.poll()) != null) {
730           long bucketBytesToFree = (bytesToFreeWithExtra - bytesFreed) / remainingBuckets;
731           bytesFreed += bucketGroup.free(bucketBytesToFree);
732           remainingBuckets--;
733         }
734       }
735 
736       // Even after the above free we might still need freeing because of the
737       // De-fragmentation of the buckets (also called Slab Calcification problem), i.e
738       // there might be some buckets where the occupancy is very sparse and thus are not
739       // yielding the free for the other bucket sizes, the fix for this to evict some
740       // of the buckets, we do this by evicting the buckets that are least fulled
741       freeEntireBuckets(DEFAULT_FREE_ENTIRE_BLOCK_FACTOR *
742           bucketSizesAboveThresholdCount(1.0f));
743 
744       if (LOG.isDebugEnabled()) {
745         long single = bucketSingle.totalSize();
746         long multi = bucketMulti.totalSize();
747         long memory = bucketMemory.totalSize();
748         if (LOG.isDebugEnabled()) {
749           LOG.debug("Bucket cache free space completed; " + "freed="
750             + StringUtils.byteDesc(bytesFreed) + ", " + "total="
751             + StringUtils.byteDesc(totalSize) + ", " + "single="
752             + StringUtils.byteDesc(single) + ", " + "multi="
753             + StringUtils.byteDesc(multi) + ", " + "memory="
754             + StringUtils.byteDesc(memory));
755         }
756       }
757 
758     } catch (Throwable t) {
759       LOG.warn("Failed freeing space", t);
760     } finally {
761       cacheStats.evict();
762       freeInProgress = false;
763       freeSpaceLock.unlock();
764     }
765   }
766 
767   // This handles flushing the RAM cache to IOEngine.
768   @VisibleForTesting
769   class WriterThread extends HasThread {
770     private final BlockingQueue<RAMQueueEntry> inputQueue;
771     private volatile boolean writerEnabled = true;
772 
773     WriterThread(BlockingQueue<RAMQueueEntry> queue) {
774       super("BucketCacheWriterThread");
775       this.inputQueue = queue;
776     }
777 
778     // Used for test
779     @VisibleForTesting
780     void disableWriter() {
781       this.writerEnabled = false;
782     }
783 
784     public void run() {
785       List<RAMQueueEntry> entries = new ArrayList<RAMQueueEntry>();
786       try {
787         while (cacheEnabled && writerEnabled) {
788           try {
789             try {
790               // Blocks
791               entries = getRAMQueueEntries(inputQueue, entries);
792             } catch (InterruptedException ie) {
793               if (!cacheEnabled) break;
794             }
795             doDrain(entries);
796           } catch (Exception ioe) {
797             LOG.error("WriterThread encountered error", ioe);
798           }
799         }
800       } catch (Throwable t) {
801         LOG.warn("Failed doing drain", t);
802       }
803       LOG.info(this.getName() + " exiting, cacheEnabled=" + cacheEnabled);
804     }
805 
806     /**
807      * Flush the entries in ramCache to IOEngine and add bucket entry to backingMap.
808      * Process all that are passed in even if failure being sure to remove from ramCache else we'll
809      * never undo the references and we'll OOME.
810      * @param entries Presumes list passed in here will be processed by this invocation only. No
811      * interference expected.
812      * @throws InterruptedException
813      */
814     @VisibleForTesting
815     void doDrain(final List<RAMQueueEntry> entries) throws InterruptedException {
816       if (entries.isEmpty()) {
817         return;
818       }
819       // This method is a little hard to follow. We run through the passed in entries and for each
820       // successful add, we add a non-null BucketEntry to the below bucketEntries.  Later we must
821       // do cleanup making sure we've cleared ramCache of all entries regardless of whether we
822       // successfully added the item to the bucketcache; if we don't do the cleanup, we'll OOME by
823       // filling ramCache.  We do the clean up by again running through the passed in entries
824       // doing extra work when we find a non-null bucketEntries corresponding entry.
825       final int size = entries.size();
826       BucketEntry[] bucketEntries = new BucketEntry[size];
827       // Index updated inside loop if success or if we can't succeed. We retry if cache is full
828       // when we go to add an entry by going around the loop again without upping the index.
829       int index = 0;
830       while (cacheEnabled && index < size) {
831         RAMQueueEntry re = null;
832         try {
833           re = entries.get(index);
834           if (re == null) {
835             LOG.warn("Couldn't get entry or changed on us; who else is messing with it?");
836             index++;
837             continue;
838           }
839           BucketEntry bucketEntry =
840             re.writeToCache(ioEngine, bucketAllocator, deserialiserMap, realCacheSize);
841           // Successfully added.  Up index and add bucketEntry. Clear io exceptions.
842           bucketEntries[index] = bucketEntry;
843           if (ioErrorStartTime > 0) {
844             ioErrorStartTime = -1;
845           }
846           index++;
847         } catch (BucketAllocatorException fle) {
848           LOG.warn("Failed allocation for " + (re == null ? "" : re.getKey()) + "; " + fle);
849           // Presume can't add. Too big? Move index on. Entry will be cleared from ramCache below.
850           bucketEntries[index] = null;
851           index++;
852         } catch (CacheFullException cfe) {
853           // Cache full when we tried to add. Try freeing space and then retrying (don't up index)
854           if (!freeInProgress) {
855             freeSpace("Full!");
856           } else {
857             Thread.sleep(50);
858           }
859         } catch (IOException ioex) {
860           // Hopefully transient. Retry. checkIOErrorIsTolerated disables cache if problem.
861           LOG.error("Failed writing to bucket cache", ioex);
862           checkIOErrorIsTolerated();
863         }
864       }
865 
866       // Make sure data pages are written on media before we update maps.
867       try {
868         ioEngine.sync();
869       } catch (IOException ioex) {
870         LOG.error("Failed syncing IO engine", ioex);
871         checkIOErrorIsTolerated();
872         // Since we failed sync, free the blocks in bucket allocator
873         for (int i = 0; i < entries.size(); ++i) {
874           if (bucketEntries[i] != null) {
875             bucketAllocator.freeBlock(bucketEntries[i].offset());
876             bucketEntries[i] = null;
877           }
878         }
879       }
880 
881       // Now add to backingMap if successfully added to bucket cache.  Remove from ramCache if
882       // success or error.
883       for (int i = 0; i < size; ++i) {
884         BlockCacheKey key = entries.get(i).getKey();
885         // Only add if non-null entry.
886         if (bucketEntries[i] != null) {
887           backingMap.put(key, bucketEntries[i]);
888         }
889         // Always remove from ramCache even if we failed adding it to the block cache above.
890         RAMQueueEntry ramCacheEntry = ramCache.remove(key);
891         if (ramCacheEntry != null) {
892           heapSize.addAndGet(-1 * entries.get(i).getData().heapSize());
893         } else if (bucketEntries[i] != null){
894           // Block should have already been evicted. Remove it and free space.
895           ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntries[i].offset());
896           try {
897             lock.writeLock().lock();
898             if (backingMap.remove(key, bucketEntries[i])) {
899               blockEvicted(key, bucketEntries[i], false);
900             }
901           } finally {
902             lock.writeLock().unlock();
903           }
904         }
905       }
906 
907       long used = bucketAllocator.getUsedSize();
908       if (used > acceptableSize()) {
909         freeSpace("Used=" + used + " > acceptable=" + acceptableSize());
910       }
911       return;
912     }
913   }
914 
915   /**
916    * Blocks until elements available in <code>q</code> then tries to grab as many as possible
917    * before returning.
918    * @param recepticle Where to stash the elements taken from queue. We clear before we use it
919    * just in case.
920    * @param q The queue to take from.
921    * @return <code>receptical laden with elements taken from the queue or empty if none found.
922    */
923   @VisibleForTesting
924   static List<RAMQueueEntry> getRAMQueueEntries(final BlockingQueue<RAMQueueEntry> q,
925       final List<RAMQueueEntry> receptical)
926   throws InterruptedException {
927     // Clear sets all entries to null and sets size to 0. We retain allocations. Presume it
928     // ok even if list grew to accommodate thousands.
929     receptical.clear();
930     receptical.add(q.take());
931     q.drainTo(receptical);
932     return receptical;
933   }
934 
935   private void persistToFile() throws IOException {
936     assert !cacheEnabled;
937     FileOutputStream fos = null;
938     ObjectOutputStream oos = null;
939     try {
940       if (!ioEngine.isPersistent()) {
941         throw new IOException("Attempt to persist non-persistent cache mappings!");
942       }
943       fos = new FileOutputStream(persistencePath, false);
944       oos = new ObjectOutputStream(fos);
945       oos.writeLong(cacheCapacity);
946       oos.writeUTF(ioEngine.getClass().getName());
947       oos.writeUTF(backingMap.getClass().getName());
948       oos.writeObject(deserialiserMap);
949       oos.writeObject(backingMap);
950     } finally {
951       if (oos != null) oos.close();
952       if (fos != null) fos.close();
953     }
954   }
955 
956   @SuppressWarnings("unchecked")
957   private void retrieveFromFile(int[] bucketSizes) throws IOException, BucketAllocatorException,
958       ClassNotFoundException {
959     File persistenceFile = new File(persistencePath);
960     if (!persistenceFile.exists()) {
961       return;
962     }
963     assert !cacheEnabled;
964     FileInputStream fis = null;
965     ObjectInputStream ois = null;
966     try {
967       if (!ioEngine.isPersistent())
968         throw new IOException(
969             "Attempt to restore non-persistent cache mappings!");
970       fis = new FileInputStream(persistencePath);
971       ois = new ObjectInputStream(fis);
972       long capacitySize = ois.readLong();
973       if (capacitySize != cacheCapacity)
974         throw new IOException("Mismatched cache capacity:"
975             + StringUtils.byteDesc(capacitySize) + ", expected: "
976             + StringUtils.byteDesc(cacheCapacity));
977       String ioclass = ois.readUTF();
978       String mapclass = ois.readUTF();
979       if (!ioEngine.getClass().getName().equals(ioclass))
980         throw new IOException("Class name for IO engine mismatch: " + ioclass
981             + ", expected:" + ioEngine.getClass().getName());
982       if (!backingMap.getClass().getName().equals(mapclass))
983         throw new IOException("Class name for cache map mismatch: " + mapclass
984             + ", expected:" + backingMap.getClass().getName());
985       UniqueIndexMap<Integer> deserMap = (UniqueIndexMap<Integer>) ois
986           .readObject();
987       ConcurrentHashMap<BlockCacheKey, BucketEntry> backingMapFromFile =
988           (ConcurrentHashMap<BlockCacheKey, BucketEntry>) ois.readObject();
989       BucketAllocator allocator = new BucketAllocator(cacheCapacity, bucketSizes,
990         backingMapFromFile, realCacheSize);
991       bucketAllocator = allocator;
992       deserialiserMap = deserMap;
993       backingMap = backingMapFromFile;
994     } finally {
995       if (ois != null) ois.close();
996       if (fis != null) fis.close();
997       if (!persistenceFile.delete()) {
998         throw new IOException("Failed deleting persistence file "
999             + persistenceFile.getAbsolutePath());
1000       }
1001     }
1002   }
1003 
1004   /**
1005    * Check whether we tolerate IO error this time. If the duration of IOEngine
1006    * throwing errors exceeds ioErrorsDurationTimeTolerated, we will disable the
1007    * cache
1008    */
1009   private void checkIOErrorIsTolerated() {
1010     long now = EnvironmentEdgeManager.currentTime();
1011     if (this.ioErrorStartTime > 0) {
1012       if (cacheEnabled && (now - ioErrorStartTime) > this.ioErrorsTolerationDuration) {
1013         LOG.error("IO errors duration time has exceeded " + ioErrorsTolerationDuration +
1014           "ms, disabling cache, please check your IOEngine");
1015         disableCache();
1016       }
1017     } else {
1018       this.ioErrorStartTime = now;
1019     }
1020   }
1021 
1022   /**
1023    * Used to shut down the cache -or- turn it off in the case of something broken.
1024    */
1025   private void disableCache() {
1026     if (!cacheEnabled) return;
1027     cacheEnabled = false;
1028     ioEngine.shutdown();
1029     this.scheduleThreadPool.shutdown();
1030     for (int i = 0; i < writerThreads.length; ++i) writerThreads[i].interrupt();
1031     this.ramCache.clear();
1032     if (!ioEngine.isPersistent() || persistencePath == null) {
1033       // If persistent ioengine and a path, we will serialize out the backingMap.
1034       this.backingMap.clear();
1035     }
1036   }
1037 
1038   private void join() throws InterruptedException {
1039     for (int i = 0; i < writerThreads.length; ++i)
1040       writerThreads[i].join();
1041   }
1042 
1043   @Override
1044   public void shutdown() {
1045     disableCache();
1046     LOG.info("Shutdown bucket cache: IO persistent=" + ioEngine.isPersistent()
1047         + "; path to write=" + persistencePath);
1048     if (ioEngine.isPersistent() && persistencePath != null) {
1049       try {
1050         join();
1051         persistToFile();
1052       } catch (IOException ex) {
1053         LOG.error("Unable to persist data on exit: " + ex.toString(), ex);
1054       } catch (InterruptedException e) {
1055         LOG.warn("Failed to persist data on exit", e);
1056       }
1057     }
1058   }
1059 
1060   @Override
1061   public CacheStats getStats() {
1062     return cacheStats;
1063   }
1064 
1065   public BucketAllocator getAllocator() {
1066     return this.bucketAllocator;
1067   }
1068 
1069   @Override
1070   public long heapSize() {
1071     return this.heapSize.get();
1072   }
1073 
1074   @Override
1075   public long size() {
1076     return this.realCacheSize.get();
1077   }
1078 
1079   @Override
1080   public long getFreeSize() {
1081     return this.bucketAllocator.getFreeSize();
1082   }
1083 
1084   @Override
1085   public long getBlockCount() {
1086     return this.blockNumber.get();
1087   }
1088 
1089   @Override
1090   public long getCurrentSize() {
1091     return this.bucketAllocator.getUsedSize();
1092   }
1093 
1094   /**
1095    * Evicts all blocks for a specific HFile.
1096    * <p>
1097    * This is used for evict-on-close to remove all blocks of a specific HFile.
1098    *
1099    * @return the number of blocks evicted
1100    */
1101   @Override
1102   public int evictBlocksByHfileName(String hfileName) {
1103     Set<BlockCacheKey> keySet = blocksByHFile.subSet(
1104         new BlockCacheKey(hfileName, Long.MIN_VALUE), true,
1105         new BlockCacheKey(hfileName, Long.MAX_VALUE), true);
1106 
1107     int numEvicted = 0;
1108     for (BlockCacheKey key : keySet) {
1109       if (evictBlock(key)) {
1110           ++numEvicted;
1111       }
1112     }
1113 
1114     return numEvicted;
1115   }
1116 
1117   /**
1118    * Item in cache. We expect this to be where most memory goes. Java uses 8
1119    * bytes just for object headers; after this, we want to use as little as
1120    * possible - so we only use 8 bytes, but in order to do so we end up messing
1121    * around with all this Java casting stuff. Offset stored as 5 bytes that make
1122    * up the long. Doubt we'll see devices this big for ages. Offsets are divided
1123    * by 256. So 5 bytes gives us 256TB or so.
1124    */
1125   static class BucketEntry implements Serializable {
1126     private static final long serialVersionUID = -6741504807982257534L;
1127 
1128     // access counter comparator, descending order
1129     static final Comparator<BucketEntry> COMPARATOR = new Comparator<BucketCache.BucketEntry>() {
1130 
1131       @Override
1132       public int compare(BucketEntry o1, BucketEntry o2) {
1133         return Long.compare(o2.accessCounter, o1.accessCounter);
1134       }
1135     };
1136 
1137     private int offsetBase;
1138     private int length;
1139     private byte offset1;
1140     byte deserialiserIndex;
1141     private volatile long accessCounter;
1142     private BlockPriority priority;
1143     /**
1144      * Time this block was cached.  Presumes we are created just before we are added to the cache.
1145      */
1146     private final long cachedTime = System.nanoTime();
1147 
1148     BucketEntry(long offset, int length, long accessCounter, boolean inMemory) {
1149       setOffset(offset);
1150       this.length = length;
1151       this.accessCounter = accessCounter;
1152       if (inMemory) {
1153         this.priority = BlockPriority.MEMORY;
1154       } else {
1155         this.priority = BlockPriority.SINGLE;
1156       }
1157     }
1158 
1159     long offset() { // Java has no unsigned numbers
1160       long o = ((long) offsetBase) & 0xFFFFFFFFL; //This needs the L cast otherwise it will be sign extended as a negative number.
1161       o += (((long) (offset1)) & 0xFF) << 32; //The 0xFF here does not need the L cast because it is treated as a positive int.
1162       return o << 8;
1163     }
1164 
1165     private void setOffset(long value) {
1166       assert (value & 0xFF) == 0;
1167       value >>= 8;
1168       offsetBase = (int) value;
1169       offset1 = (byte) (value >> 32);
1170     }
1171 
1172     public int getLength() {
1173       return length;
1174     }
1175 
1176     protected CacheableDeserializer<Cacheable> deserializerReference(
1177         UniqueIndexMap<Integer> deserialiserMap) {
1178       return CacheableDeserializerIdManager.getDeserializer(deserialiserMap
1179           .unmap(deserialiserIndex));
1180     }
1181 
1182     protected void setDeserialiserReference(
1183         CacheableDeserializer<Cacheable> deserializer,
1184         UniqueIndexMap<Integer> deserialiserMap) {
1185       this.deserialiserIndex = ((byte) deserialiserMap.map(deserializer
1186           .getDeserialiserIdentifier()));
1187     }
1188 
1189     /**
1190      * Block has been accessed. Update its local access counter.
1191      */
1192     public void access(long accessCounter) {
1193       this.accessCounter = accessCounter;
1194       if (this.priority == BlockPriority.SINGLE) {
1195         this.priority = BlockPriority.MULTI;
1196       }
1197     }
1198 
1199     public BlockPriority getPriority() {
1200       return this.priority;
1201     }
1202 
1203     public long getCachedTime() {
1204       return cachedTime;
1205     }
1206   }
1207 
1208   /**
1209    * Used to group bucket entries into priority buckets. There will be a
1210    * BucketEntryGroup for each priority (single, multi, memory). Once bucketed,
1211    * the eviction algorithm takes the appropriate number of elements out of each
1212    * according to configuration parameters and their relative sizes.
1213    */
1214   private class BucketEntryGroup implements Comparable<BucketEntryGroup> {
1215 
1216     private CachedEntryQueue queue;
1217     private long totalSize = 0;
1218     private long bucketSize;
1219 
1220     public BucketEntryGroup(long bytesToFree, long blockSize, long bucketSize) {
1221       this.bucketSize = bucketSize;
1222       queue = new CachedEntryQueue(bytesToFree, blockSize);
1223       totalSize = 0;
1224     }
1225 
1226     public void add(Map.Entry<BlockCacheKey, BucketEntry> block) {
1227       totalSize += block.getValue().getLength();
1228       queue.add(block);
1229     }
1230 
1231     public long free(long toFree) {
1232       Map.Entry<BlockCacheKey, BucketEntry> entry;
1233       long freedBytes = 0;
1234       while ((entry = queue.pollLast()) != null) {
1235         evictBlock(entry.getKey());
1236         freedBytes += entry.getValue().getLength();
1237         if (freedBytes >= toFree) {
1238           return freedBytes;
1239         }
1240       }
1241       return freedBytes;
1242     }
1243 
1244     public long overflow() {
1245       return totalSize - bucketSize;
1246     }
1247 
1248     public long totalSize() {
1249       return totalSize;
1250     }
1251 
1252     @Override
1253     public int compareTo(BucketEntryGroup that) {
1254       return Long.compare(this.overflow(), that.overflow());
1255     }
1256 
1257     @Override
1258     public boolean equals(Object that) {
1259       return this == that;
1260     }
1261 
1262   }
1263 
1264   /**
1265    * Block Entry stored in the memory with key,data and so on
1266    */
1267   @VisibleForTesting
1268   static class RAMQueueEntry {
1269     private BlockCacheKey key;
1270     private Cacheable data;
1271     private long accessCounter;
1272     private boolean inMemory;
1273 
1274     public RAMQueueEntry(BlockCacheKey bck, Cacheable data, long accessCounter,
1275         boolean inMemory) {
1276       this.key = bck;
1277       this.data = data;
1278       this.accessCounter = accessCounter;
1279       this.inMemory = inMemory;
1280     }
1281 
1282     public Cacheable getData() {
1283       return data;
1284     }
1285 
1286     public BlockCacheKey getKey() {
1287       return key;
1288     }
1289 
1290     public void access(long accessCounter) {
1291       this.accessCounter = accessCounter;
1292     }
1293 
1294     public BucketEntry writeToCache(final IOEngine ioEngine,
1295         final BucketAllocator bucketAllocator,
1296         final UniqueIndexMap<Integer> deserialiserMap,
1297         final AtomicLong realCacheSize) throws CacheFullException, IOException,
1298         BucketAllocatorException {
1299       int len = data.getSerializedLength();
1300       // This cacheable thing can't be serialized
1301       if (len == 0) return null;
1302       long offset = bucketAllocator.allocateBlock(len);
1303       BucketEntry bucketEntry = new BucketEntry(offset, len, accessCounter, inMemory);
1304       bucketEntry.setDeserialiserReference(data.getDeserializer(), deserialiserMap);
1305       try {
1306         if (data instanceof HFileBlock) {
1307           // If an instance of HFileBlock, save on some allocations.
1308           HFileBlock block = (HFileBlock)data;
1309           ByteBuffer sliceBuf = block.getBufferReadOnly();
1310           ByteBuffer metadata = block.getMetaData();
1311           if (LOG.isTraceEnabled()) {
1312             LOG.trace("Write offset=" + offset + ", len=" + len);
1313           }
1314           ioEngine.write(sliceBuf, offset);
1315           ioEngine.write(metadata, offset + len - metadata.limit());
1316         } else {
1317           ByteBuffer bb = ByteBuffer.allocate(len);
1318           data.serialize(bb);
1319           ioEngine.write(bb, offset);
1320         }
1321       } catch (IOException ioe) {
1322         // free it in bucket allocator
1323         bucketAllocator.freeBlock(offset);
1324         throw ioe;
1325       }
1326 
1327       realCacheSize.addAndGet(len);
1328       return bucketEntry;
1329     }
1330   }
1331 
1332   /**
1333    * Only used in test
1334    * @throws InterruptedException
1335    */
1336   void stopWriterThreads() throws InterruptedException {
1337     for (WriterThread writerThread : writerThreads) {
1338       writerThread.disableWriter();
1339       writerThread.interrupt();
1340       writerThread.join();
1341     }
1342   }
1343 
1344   @Override
1345   public Iterator<CachedBlock> iterator() {
1346     // Don't bother with ramcache since stuff is in here only a little while.
1347     final Iterator<Map.Entry<BlockCacheKey, BucketEntry>> i =
1348         this.backingMap.entrySet().iterator();
1349     return new Iterator<CachedBlock>() {
1350       private final long now = System.nanoTime();
1351 
1352       @Override
1353       public boolean hasNext() {
1354         return i.hasNext();
1355       }
1356 
1357       @Override
1358       public CachedBlock next() {
1359         final Map.Entry<BlockCacheKey, BucketEntry> e = i.next();
1360         return new CachedBlock() {
1361           @Override
1362           public String toString() {
1363             return BlockCacheUtil.toString(this, now);
1364           }
1365 
1366           @Override
1367           public BlockPriority getBlockPriority() {
1368             return e.getValue().getPriority();
1369           }
1370 
1371           @Override
1372           public BlockType getBlockType() {
1373             // Not held by BucketEntry.  Could add it if wanted on BucketEntry creation.
1374             return null;
1375           }
1376 
1377           @Override
1378           public long getOffset() {
1379             return e.getKey().getOffset();
1380           }
1381 
1382           @Override
1383           public long getSize() {
1384             return e.getValue().getLength();
1385           }
1386 
1387           @Override
1388           public long getCachedTime() {
1389             return e.getValue().getCachedTime();
1390           }
1391 
1392           @Override
1393           public String getFilename() {
1394             return e.getKey().getHfileName();
1395           }
1396 
1397           @Override
1398           public int compareTo(CachedBlock other) {
1399             int diff = this.getFilename().compareTo(other.getFilename());
1400             if (diff != 0) return diff;
1401 
1402             diff = Long.compare(this.getOffset(), other.getOffset());
1403             if (diff != 0) return diff;
1404             if (other.getCachedTime() < 0 || this.getCachedTime() < 0) {
1405               throw new IllegalStateException("" + this.getCachedTime() + ", " +
1406                 other.getCachedTime());
1407             }
1408             return Long.compare(other.getCachedTime(), this.getCachedTime());
1409           }
1410 
1411           @Override
1412           public int hashCode() {
1413             return e.getKey().hashCode();
1414           }
1415 
1416           @Override
1417           public boolean equals(Object obj) {
1418             if (obj instanceof CachedBlock) {
1419               CachedBlock cb = (CachedBlock)obj;
1420               return compareTo(cb) == 0;
1421             } else {
1422               return false;
1423             }
1424           }
1425         };
1426       }
1427 
1428       @Override
1429       public void remove() {
1430         throw new UnsupportedOperationException();
1431       }
1432     };
1433   }
1434 
1435   @Override
1436   public BlockCache[] getBlockCaches() {
1437     return null;
1438   }
1439 }