[转] HBase-1.2.4LruBlockCache实现分析

原文链接:http://blog.csdn.net/lipeng_bigdata/article/details/53410373


一、简介

      BlockCache是Hbase中的一个重要特性,相比于写数据时缓存为Memstore,读数据时的缓存则为BlockCache。
      LruBlockCache是HBase中BlockCache的默认实现,它采用严格的LRU算法来淘汰Block。

二、缓存级别

      目前有三种缓存级别,定义在BlockPriority中,如下:

[java]  view plain  copy
  1. public enum BlockPriority {  
  2.   /** 
  3.    * Accessed a single time (used for scan-resistance) 
  4.    */  
  5.   SINGLE,  
  6.   /** 
  7.    * Accessed multiple times 
  8.    */  
  9.   MULTI,  
  10.   /** 
  11.    * Block from in-memory store 
  12.    */  
  13.   MEMORY  
  14. }  

      1、SINGLE:主要用于scan等,避免大量的这种一次的访问导致缓存替换;

      2、MULTI:多次缓存;

      3、MEMORY:常驻缓存的,比如meta信息等。

三、缓存实现分析

      LruBlockCache缓存的实现在方法cacheBlock()中,实现逻辑如下:

      1、首先需要判断需要缓存的数据大小是否超过最大块大小,按照2%的频率记录warn类型log并返回;

      2、从缓存map中根据cacheKey尝试获取已缓存数据块cb;

      3、如果已经缓存过,比对下内容,如果内容不一样,抛出异常,否则记录warn类型log并返回;

      4、获取当前缓存大小currentSize,获取可以接受的缓存大小currentAcceptableSize,计算硬性限制大小hardLimitSize;

      5、如果当前大小超过硬性限制,当回收没在执行时,执行回收并返回,否则直接返回;

      6、利用cacheKey、数据buf等构造Lru缓存数据块实例cb;

      7、将cb放置入map缓存中;

      8、元素个数原子性增1;

      9、如果新大小超过当前可以接受的大小,且未执行回收过程中,执行内存回收。

      详细代码如下,可自行阅读分析:

[java]  view plain  copy
  1.  // BlockCache implementation  
  2.   
  3.  /** 
  4.   * Cache the block with the specified name and buffer. 
  5.   * <p> 
  6.   * It is assumed this will NOT be called on an already cached block. In rare cases (HBASE-8547) 
  7.   * this can happen, for which we compare the buffer contents. 
  8.   * @param cacheKey block's cache key 
  9.   * @param buf block buffer 
  10.   * @param inMemory if block is in-memory 
  11.   * @param cacheDataInL1 
  12.   */  
  13.  @Override  
  14.  public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory,  
  15.      final boolean cacheDataInL1) {  
  16.   
  17. // 首先需要判断需要缓存的数据大小是否超过最大块大小  
  18.    if (buf.heapSize() > maxBlockSize) {  
  19.      // If there are a lot of blocks that are too  
  20.      // big this can make the logs way too noisy.  
  21.      // So we log 2%  
  22.      if (stats.failInsert() % 50 == 0) {  
  23.        LOG.warn("Trying to cache too large a block "  
  24.            + cacheKey.getHfileName() + " @ "  
  25.            + cacheKey.getOffset()  
  26.            + " is " + buf.heapSize()  
  27.            + " which is larger than " + maxBlockSize);  
  28.      }  
  29.      return;  
  30.    }  
  31.   
  32.    // 从缓存map中根据cacheKey尝试获取已缓存数据块  
  33.    LruCachedBlock cb = map.get(cacheKey);  
  34.    if (cb != null) {// 如果已经缓存过  
  35.      // compare the contents, if they are not equal, we are in big trouble  
  36.      if (compare(buf, cb.getBuffer()) != 0) {// 比对缓存内容,如果不相等,抛出异常,否则记录warn日志  
  37.        throw new RuntimeException("Cached block contents differ, which should not have happened."  
  38.          + "cacheKey:" + cacheKey);  
  39.      }  
  40.      String msg = "Cached an already cached block: " + cacheKey + " cb:" + cb.getCacheKey();  
  41.      msg += ". This is harmless and can happen in rare cases (see HBASE-8547)";  
  42.      LOG.warn(msg);  
  43.      return;  
  44.    }  
  45.      
  46.    // 获取当前缓存大小  
  47.    long currentSize = size.get();  
  48.      
  49.    // 获取可以接受的缓存大小  
  50.    long currentAcceptableSize = acceptableSize();  
  51.      
  52.    // 计算硬性限制大小  
  53.    long hardLimitSize = (long) (hardCapacityLimitFactor * currentAcceptableSize);  
  54.      
  55.    if (currentSize >= hardLimitSize) {// 如果当前大小超过硬性限制,当回收没在执行时,执行回收并返回  
  56.      stats.failInsert();  
  57.      if (LOG.isTraceEnabled()) {  
  58.        LOG.trace("LruBlockCache current size " + StringUtils.byteDesc(currentSize)  
  59.          + " has exceeded acceptable size " + StringUtils.byteDesc(currentAcceptableSize) + "  too many."  
  60.          + " the hard limit size is " + StringUtils.byteDesc(hardLimitSize) + ", failed to put cacheKey:"  
  61.          + cacheKey + " into LruBlockCache.");  
  62.      }  
  63.      if (!evictionInProgress) {// 当回收没在执行时,执行回收并返回  
  64.        runEviction();  
  65.      }  
  66.      return;  
  67.    }  
  68.      
  69.    // 利用cacheKey、数据buf等构造Lru缓存数据块实例  
  70.    cb = new LruCachedBlock(cacheKey, buf, count.incrementAndGet(), inMemory);  
  71.    long newSize = updateSizeMetrics(cb, false);  
  72.      
  73.    // 放置入map缓存中  
  74.    map.put(cacheKey, cb);  
  75.      
  76.    // 元素个数原子性增1  
  77.    long val = elements.incrementAndGet();  
  78.    if (LOG.isTraceEnabled()) {  
  79.      long size = map.size();  
  80.      assertCounterSanity(size, val);  
  81.    }  
  82.      
  83.    // 如果新大小超过当前可以接受的大小,且未执行回收过程中  
  84.    if (newSize > currentAcceptableSize && !evictionInProgress) {  
  85.      runEviction();// 执行内存回收  
  86.    }  
  87.  }  
四、淘汰缓存实现分析

      淘汰缓存的实现方式有两种:

      1、第一种是在主线程中执行缓存淘汰;

      2、第二种是在一个专门的淘汰线程中通过持有对外部类LruBlockCache的弱引用WeakReference来执行缓存淘汰。

      应用那种方式,取决于构造函数中的boolean参数evictionThread,如下:

[java]  view plain  copy
  1. if(evictionThread) {  
  2.   this.evictionThread = new EvictionThread(this);  
  3.   this.evictionThread.start(); // FindBugs SC_START_IN_CTOR  
  4. else {  
  5.   this.evictionThread = null;  
  6. }  
      而在执行淘汰缓存的runEviction()方法中,有如下判断:

[java]  view plain  copy
  1. /** 
  2.  * Multi-threaded call to run the eviction process. 
  3.  * 多线程调用以执行回收过程 
  4.  */  
  5. private void runEviction() {  
  6.   if(evictionThread == null) {// 如果未指定回收线程  
  7.     evict();  
  8.   } else {// 如果执行了回收线程  
  9.     evictionThread.evict();  
  10.   }  
  11. }  
        而EvictionThread的evict()实现如下:

[java]  view plain  copy
  1. @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NN_NAKED_NOTIFY",  
  2.     justification="This is what we want")  
  3. public void evict() {  
  4.   synchronized(this) {  
  5.     this.notifyAll();  
  6.   }  
  7. }  
        通过synchronized获取EvictionThread线程的对象锁,然后主线程通过回收线程对象的notifyAll唤醒EvictionThread线程,那么这个线程是何时wait的呢?答案就在其run()方法中,notifyAll()之后,线程run()方法得以继续执行:

[java]  view plain  copy
  1. @Override  
  2. public void run() {  
  3.   enteringRun = true;  
  4.   while (this.go) {  
  5.     synchronized(this) {  
  6.       try {  
  7.         this.wait(1000 * 10/*Don't wait for ever*/);  
  8.       } catch(InterruptedException e) {  
  9.         LOG.warn("Interrupted eviction thread ", e);  
  10.         Thread.currentThread().interrupt();  
  11.       }  
  12.     }  
  13.     LruBlockCache cache = this.cache.get();  
  14.     if (cache == nullbreak;  
  15.     cache.evict();  
  16.   }  
  17. }  
        线程会wait10s,放弃对象锁,在notifyAll()后,继续执行后面的淘汰流程,即:

[java]  view plain  copy
  1. /** 
  2.  * Eviction method. 
  3.  */  
  4. void evict() {  
  5.   
  6.   // Ensure only one eviction at a time  
  7. / 通过可重入互斥锁ReentrantLock确保同一时刻只有一个回收在执行  
  8.   if(!evictionLock.tryLock()) return;  
  9.   
  10.   try {  
  11.       
  12.     // 标志位,是否正在进行回收过程  
  13.     evictionInProgress = true;  
  14.       
  15.     // 当前缓存大小  
  16.     long currentSize = this.size.get();  
  17.     // 计算应该释放的缓冲大小bytesToFree  
  18.     long bytesToFree = currentSize - minSize();  
  19.   
  20.     if (LOG.isTraceEnabled()) {  
  21.       LOG.trace("Block cache LRU eviction started; Attempting to free " +  
  22.         StringUtils.byteDesc(bytesToFree) + " of total=" +  
  23.         StringUtils.byteDesc(currentSize));  
  24.     }  
  25.   
  26.     // 如果需要回收的大小小于等于0,直接返回  
  27.     if(bytesToFree <= 0return;  
  28.   
  29.     // Instantiate priority buckets  
  30.     // 实例化优先级队列:single、multi、memory  
  31.     BlockBucket bucketSingle = new BlockBucket("single", bytesToFree, blockSize,  
  32.         singleSize());  
  33.     BlockBucket bucketMulti = new BlockBucket("multi", bytesToFree, blockSize,  
  34.         multiSize());  
  35.     BlockBucket bucketMemory = new BlockBucket("memory", bytesToFree, blockSize,  
  36.         memorySize());  
  37.   
  38.     // Scan entire map putting into appropriate buckets  
  39.     // 扫描缓存,分别加入上述三个优先级队列  
  40.     for(LruCachedBlock cachedBlock : map.values()) {  
  41.       switch(cachedBlock.getPriority()) {  
  42.         case SINGLE: {  
  43.           bucketSingle.add(cachedBlock);  
  44.           break;  
  45.         }  
  46.         case MULTI: {  
  47.           bucketMulti.add(cachedBlock);  
  48.           break;  
  49.         }  
  50.         case MEMORY: {  
  51.           bucketMemory.add(cachedBlock);  
  52.           break;  
  53.         }  
  54.       }  
  55.     }  
  56.   
  57.     long bytesFreed = 0;  
  58.     if (forceInMemory || memoryFactor > 0.999f) {// 如果memoryFactor或者InMemory缓存超过99.9%,  
  59.       long s = bucketSingle.totalSize();  
  60.       long m = bucketMulti.totalSize();  
  61.       if (bytesToFree > (s + m)) {// 如果需要回收的缓存超过则全部回收Single、Multi中的缓存大小和,则全部回收Single、Multi中的缓存,剩余的则从InMemory中回收  
  62.         // this means we need to evict blocks in memory bucket to make room,  
  63.         // so the single and multi buckets will be emptied  
  64.         bytesFreed = bucketSingle.free(s);  
  65.         bytesFreed += bucketMulti.free(m);  
  66.         if (LOG.isTraceEnabled()) {  
  67.           LOG.trace("freed " + StringUtils.byteDesc(bytesFreed) +  
  68.             " from single and multi buckets");  
  69.         }  
  70.         // 剩余的则从InMemory中回收  
  71.         bytesFreed += bucketMemory.free(bytesToFree - bytesFreed);  
  72.         if (LOG.isTraceEnabled()) {  
  73.           LOG.trace("freed " + StringUtils.byteDesc(bytesFreed) +  
  74.             " total from all three buckets ");  
  75.         }  
  76.       } else {// 否则,不需要从InMemory中回收,按照如下策略回收Single、Multi中的缓存:尝试让single-bucket和multi-bucket的比例为1:2  
  77.         // this means no need to evict block in memory bucket,  
  78.         // and we try best to make the ratio between single-bucket and  
  79.         // multi-bucket is 1:2  
  80.         long bytesRemain = s + m - bytesToFree;  
  81.         if (3 * s <= bytesRemain) {// single-bucket足够小,从multi-bucket中回收  
  82.           // single-bucket is small enough that no eviction happens for it  
  83.           // hence all eviction goes from multi-bucket  
  84.           bytesFreed = bucketMulti.free(bytesToFree);  
  85.         } else if (3 * m <= 2 * bytesRemain) {// multi-bucket足够下,从single-bucket中回收  
  86.           // multi-bucket is small enough that no eviction happens for it  
  87.           // hence all eviction goes from single-bucket  
  88.           bytesFreed = bucketSingle.free(bytesToFree);  
  89.         } else {  
  90.         // single-bucket和multi-bucket中都回收,且尽量满足回收后比例为1:2  
  91.           // both buckets need to evict some blocks  
  92.           bytesFreed = bucketSingle.free(s - bytesRemain / 3);  
  93.           if (bytesFreed < bytesToFree) {  
  94.             bytesFreed += bucketMulti.free(bytesToFree - bytesFreed);  
  95.           }  
  96.         }  
  97.       }  
  98.     } else {// 否则,从三个队列中循环回收  
  99.       PriorityQueue<BlockBucket> bucketQueue =  
  100.         new PriorityQueue<BlockBucket>(3);  
  101.   
  102.       bucketQueue.add(bucketSingle);  
  103.       bucketQueue.add(bucketMulti);  
  104.       bucketQueue.add(bucketMemory);  
  105.   
  106.       int remainingBuckets = 3;  
  107.   
  108.       BlockBucket bucket;  
  109.       while((bucket = bucketQueue.poll()) != null) {  
  110.         long overflow = bucket.overflow();  
  111.         if(overflow > 0) {  
  112.           long bucketBytesToFree = Math.min(overflow,  
  113.               (bytesToFree - bytesFreed) / remainingBuckets);  
  114.           bytesFreed += bucket.free(bucketBytesToFree);  
  115.         }  
  116.         remainingBuckets--;  
  117.       }  
  118.     }  
  119.   
  120.     if (LOG.isTraceEnabled()) {  
  121.       long single = bucketSingle.totalSize();  
  122.       long multi = bucketMulti.totalSize();  
  123.       long memory = bucketMemory.totalSize();  
  124.       LOG.trace("Block cache LRU eviction completed; " +  
  125.         "freed=" + StringUtils.byteDesc(bytesFreed) + ", " +  
  126.         "total=" + StringUtils.byteDesc(this.size.get()) + ", " +  
  127.         "single=" + StringUtils.byteDesc(single) + ", " +  
  128.         "multi=" + StringUtils.byteDesc(multi) + ", " +  
  129.         "memory=" + StringUtils.byteDesc(memory));  
  130.     }  
  131.   } finally {  
  132.     // 重置标志位,释放锁等  
  133.     stats.evict();  
  134.     evictionInProgress = false;  
  135.     evictionLock.unlock();  
  136.   }  
  137. }  

        逻辑比较清晰,如下:

        1、通过可重入互斥锁ReentrantLock确保同一时刻只有一个回收在执行;

        2、设置标志位evictionInProgress,是否正在进行回收过程为true;

        3、获取当前缓存大小currentSize;

        4、计算应该释放的缓冲大小bytesToFree:currentSize - minSize();

        5、如果需要回收的大小小于等于0,直接返回;

        6、实例化优先级队列:single、multi、memory;

        7、扫描缓存,分别加入上述三个优先级队列;

        8、如果forceInMemory或者InMemory缓存超过99.9%:

              8.1、如果需要回收的缓存超过则全部回收Single、Multi中的缓存大小和,则全部回收Single、Multi中的缓存,剩余的则从InMemory中回收(this means we need to evict blocks in memory bucket to make room,so the single and multi buckets will be emptied):

              8.2、否则,不需要从InMemory中回收,按照如下策略回收Single、Multi中的缓存:尝试让single-bucket和multi-bucket的比例为1:2:

                        8.2.1、 single-bucket足够小,从multi-bucket中回收;

                        8.2.2、 multi-bucket足够小,从single-bucket中回收;

                        8.2.3、single-bucket和multi-bucket中都回收,且尽量满足回收后比例为1:2;

        9、否则,从三个队列中循环回收;

        10、最后,重置标志位,释放锁等。

四、实例化

        参见《HBase-1.2.4 Allow block cache to be external分析》最后。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值