001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.io.hfile; 019 020import static java.util.Objects.requireNonNull; 021 022import java.lang.ref.WeakReference; 023import java.util.EnumMap; 024import java.util.Iterator; 025import java.util.List; 026import java.util.Map; 027import java.util.PriorityQueue; 028import java.util.SortedSet; 029import java.util.TreeSet; 030import java.util.concurrent.ConcurrentHashMap; 031import java.util.concurrent.Executors; 032import java.util.concurrent.ScheduledExecutorService; 033import java.util.concurrent.TimeUnit; 034import java.util.concurrent.atomic.AtomicLong; 035import java.util.concurrent.atomic.LongAdder; 036import java.util.concurrent.locks.ReentrantLock; 037import org.apache.commons.lang3.mutable.MutableObject; 038import org.apache.hadoop.conf.Configuration; 039import org.apache.hadoop.hbase.HBaseInterfaceAudience; 040import org.apache.hadoop.hbase.io.HeapSize; 041import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; 042import org.apache.hadoop.hbase.util.ClassSize; 043import org.apache.hadoop.util.StringUtils; 044import org.apache.yetus.audience.InterfaceAudience; 045import org.slf4j.Logger; 046import org.slf4j.LoggerFactory; 047 048import org.apache.hbase.thirdparty.com.google.common.base.MoreObjects; 049import org.apache.hbase.thirdparty.com.google.common.base.Objects; 050import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; 051 052/** 053 * A block cache implementation that is memory-aware using {@link HeapSize}, memory-bound using an 054 * LRU eviction algorithm, and concurrent: backed by a {@link ConcurrentHashMap} and with a 055 * non-blocking eviction thread giving constant-time {@link #cacheBlock} and {@link #getBlock} 056 * operations. 057 * </p> 058 * Contains three levels of block priority to allow for scan-resistance and in-memory families 059 * {@link org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder#setInMemory(boolean)} (An 060 * in-memory column family is a column family that should be served from memory if possible): 061 * single-access, multiple-accesses, and in-memory priority. A block is added with an in-memory 062 * priority flag if {@link org.apache.hadoop.hbase.client.ColumnFamilyDescriptor#isInMemory()}, 063 * otherwise a block becomes a single access priority the first time it is read into this block 064 * cache. If a block is accessed again while in cache, it is marked as a multiple access priority 065 * block. This delineation of blocks is used to prevent scans from thrashing the cache adding a 066 * least-frequently-used element to the eviction algorithm. 067 * <p/> 068 * Each priority is given its own chunk of the total cache to ensure fairness during eviction. Each 069 * priority will retain close to its maximum size, however, if any priority is not using its entire 070 * chunk the others are able to grow beyond their chunk size. 071 * <p/> 072 * Instantiated at a minimum with the total size and average block size. All sizes are in bytes. The 073 * block size is not especially important as this cache is fully dynamic in its sizing of blocks. It 074 * is only used for pre-allocating data structures and in initial heap estimation of the map. 075 * <p/> 076 * The detailed constructor defines the sizes for the three priorities (they should total to the 077 * <code>maximum size</code> defined). It also sets the levels that trigger and control the eviction 078 * thread. 079 * <p/> 080 * The <code>acceptable size</code> is the cache size level which triggers the eviction process to 081 * start. It evicts enough blocks to get the size below the minimum size specified. 082 * <p/> 083 * Eviction happens in a separate thread and involves a single full-scan of the map. It determines 084 * how many bytes must be freed to reach the minimum size, and then while scanning determines the 085 * fewest least-recently-used blocks necessary from each of the three priorities (would be 3 times 086 * bytes to free). It then uses the priority chunk sizes to evict fairly according to the relative 087 * sizes and usage. 088 */ 089@InterfaceAudience.Private 090public class LruBlockCache implements FirstLevelBlockCache { 091 092 private static final Logger LOG = LoggerFactory.getLogger(LruBlockCache.class); 093 094 /** 095 * Percentage of total size that eviction will evict until; e.g. if set to .8, then we will keep 096 * evicting during an eviction run till the cache size is down to 80% of the total. 097 */ 098 private static final String LRU_MIN_FACTOR_CONFIG_NAME = "hbase.lru.blockcache.min.factor"; 099 100 /** 101 * Acceptable size of cache (no evictions if {@code size < acceptable}) 102 */ 103 private static final String LRU_ACCEPTABLE_FACTOR_CONFIG_NAME = 104 "hbase.lru.blockcache.acceptable.factor"; 105 106 /** 107 * Hard capacity limit of cache, will reject any put if size > this * acceptable 108 */ 109 static final String LRU_HARD_CAPACITY_LIMIT_FACTOR_CONFIG_NAME = 110 "hbase.lru.blockcache.hard.capacity.limit.factor"; 111 private static final String LRU_SINGLE_PERCENTAGE_CONFIG_NAME = 112 "hbase.lru.blockcache.single.percentage"; 113 private static final String LRU_MULTI_PERCENTAGE_CONFIG_NAME = 114 "hbase.lru.blockcache.multi.percentage"; 115 private static final String LRU_MEMORY_PERCENTAGE_CONFIG_NAME = 116 "hbase.lru.blockcache.memory.percentage"; 117 118 /** 119 * Configuration key to force data-block always (except in-memory are too much) cached in memory 120 * for in-memory hfile, unlike inMemory, which is a column-family configuration, inMemoryForceMode 121 * is a cluster-wide configuration 122 */ 123 private static final String LRU_IN_MEMORY_FORCE_MODE_CONFIG_NAME = 124 "hbase.lru.rs.inmemoryforcemode"; 125 126 /* Default Configuration Parameters */ 127 128 /* Backing Concurrent Map Configuration */ 129 static final float DEFAULT_LOAD_FACTOR = 0.75f; 130 static final int DEFAULT_CONCURRENCY_LEVEL = 16; 131 132 /* Eviction thresholds */ 133 private static final float DEFAULT_MIN_FACTOR = 0.95f; 134 static final float DEFAULT_ACCEPTABLE_FACTOR = 0.99f; 135 136 /* Priority buckets */ 137 private static final float DEFAULT_SINGLE_FACTOR = 0.25f; 138 private static final float DEFAULT_MULTI_FACTOR = 0.50f; 139 private static final float DEFAULT_MEMORY_FACTOR = 0.25f; 140 141 private static final float DEFAULT_HARD_CAPACITY_LIMIT_FACTOR = 1.2f; 142 143 private static final boolean DEFAULT_IN_MEMORY_FORCE_MODE = false; 144 145 /* Statistics thread */ 146 private static final int STAT_THREAD_PERIOD = 60 * 5; 147 private static final String LRU_MAX_BLOCK_SIZE = "hbase.lru.max.block.size"; 148 private static final long DEFAULT_MAX_BLOCK_SIZE = 16L * 1024L * 1024L; 149 150 /** 151 * Defined the cache map as {@link ConcurrentHashMap} here, because in 152 * {@link LruBlockCache#getBlock}, we need to guarantee the atomicity of map#k (key, func). 153 * Besides, the func method must execute exactly once only when the key is present and under the 154 * lock context, otherwise the reference count will be messed up. Notice that the 155 * {@link java.util.concurrent.ConcurrentSkipListMap} can not guarantee that. Some code using 156 * #computeIfPresent also expects the supplier to be executed only once. ConcurrentHashMap can 157 * guarantee that. Other types may not. 158 */ 159 private transient final ConcurrentHashMap<BlockCacheKey, LruCachedBlock> map; 160 161 /** Eviction lock (locked when eviction in process) */ 162 private transient final ReentrantLock evictionLock = new ReentrantLock(true); 163 164 private final long maxBlockSize; 165 166 /** Volatile boolean to track if we are in an eviction process or not */ 167 private volatile boolean evictionInProgress = false; 168 169 /** Eviction thread */ 170 private transient final EvictionThread evictionThread; 171 172 /** Statistics thread schedule pool (for heavy debugging, could remove) */ 173 private transient final ScheduledExecutorService scheduleThreadPool = 174 Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder() 175 .setNameFormat("LruBlockCacheStatsExecutor").setDaemon(true).build()); 176 177 /** Current size of cache */ 178 private final AtomicLong size; 179 180 /** Current size of data blocks */ 181 private final LongAdder dataBlockSize = new LongAdder(); 182 183 /** Current size of index blocks */ 184 private final LongAdder indexBlockSize = new LongAdder(); 185 186 /** Current size of bloom blocks */ 187 private final LongAdder bloomBlockSize = new LongAdder(); 188 189 /** Current number of cached elements */ 190 private final AtomicLong elements; 191 192 /** Current number of cached data block elements */ 193 private final LongAdder dataBlockElements = new LongAdder(); 194 195 /** Current number of cached index block elements */ 196 private final LongAdder indexBlockElements = new LongAdder(); 197 198 /** Current number of cached bloom block elements */ 199 private final LongAdder bloomBlockElements = new LongAdder(); 200 201 /** Cache access count (sequential ID) */ 202 private final AtomicLong count; 203 204 /** hard capacity limit */ 205 private float hardCapacityLimitFactor; 206 207 /** Cache statistics */ 208 private final CacheStats stats; 209 210 /** Maximum allowable size of cache (block put if size > max, evict) */ 211 private long maxSize; 212 213 /** Approximate block size */ 214 private long blockSize; 215 216 /** Acceptable size of cache (no evictions if {@code size < acceptable}) */ 217 private float acceptableFactor; 218 219 /** Minimum threshold of cache (when evicting, evict until {@code size < min}) */ 220 private float minFactor; 221 222 /** Single access bucket size */ 223 private float singleFactor; 224 225 /** Multiple access bucket size */ 226 private float multiFactor; 227 228 /** In-memory bucket size */ 229 private float memoryFactor; 230 231 /** Overhead of the structure itself */ 232 private long overhead; 233 234 /** Whether in-memory hfile's data block has higher priority when evicting */ 235 private boolean forceInMemory; 236 237 /** 238 * Where to send victims (blocks evicted/missing from the cache). This is used only when we use an 239 * external cache as L2. Note: See org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache 240 */ 241 private transient BlockCache victimHandler = null; 242 243 /** 244 * Default constructor. Specify maximum size and expected average block size (approximation is 245 * fine). 246 * <p> 247 * All other factors will be calculated based on defaults specified in this class. 248 * @param maxSize maximum size of cache, in bytes 249 * @param blockSize approximate size of each block, in bytes 250 */ 251 public LruBlockCache(long maxSize, long blockSize) { 252 this(maxSize, blockSize, true); 253 } 254 255 /** 256 * Constructor used for testing. Allows disabling of the eviction thread. 257 */ 258 public LruBlockCache(long maxSize, long blockSize, boolean evictionThread) { 259 this(maxSize, blockSize, evictionThread, (int) Math.ceil(1.2 * maxSize / blockSize), 260 DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, DEFAULT_MIN_FACTOR, DEFAULT_ACCEPTABLE_FACTOR, 261 DEFAULT_SINGLE_FACTOR, DEFAULT_MULTI_FACTOR, DEFAULT_MEMORY_FACTOR, 262 DEFAULT_HARD_CAPACITY_LIMIT_FACTOR, false, DEFAULT_MAX_BLOCK_SIZE); 263 } 264 265 public LruBlockCache(long maxSize, long blockSize, boolean evictionThread, Configuration conf) { 266 this(maxSize, blockSize, evictionThread, (int) Math.ceil(1.2 * maxSize / blockSize), 267 DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, 268 conf.getFloat(LRU_MIN_FACTOR_CONFIG_NAME, DEFAULT_MIN_FACTOR), 269 conf.getFloat(LRU_ACCEPTABLE_FACTOR_CONFIG_NAME, DEFAULT_ACCEPTABLE_FACTOR), 270 conf.getFloat(LRU_SINGLE_PERCENTAGE_CONFIG_NAME, DEFAULT_SINGLE_FACTOR), 271 conf.getFloat(LRU_MULTI_PERCENTAGE_CONFIG_NAME, DEFAULT_MULTI_FACTOR), 272 conf.getFloat(LRU_MEMORY_PERCENTAGE_CONFIG_NAME, DEFAULT_MEMORY_FACTOR), 273 conf.getFloat(LRU_HARD_CAPACITY_LIMIT_FACTOR_CONFIG_NAME, DEFAULT_HARD_CAPACITY_LIMIT_FACTOR), 274 conf.getBoolean(LRU_IN_MEMORY_FORCE_MODE_CONFIG_NAME, DEFAULT_IN_MEMORY_FORCE_MODE), 275 conf.getLong(LRU_MAX_BLOCK_SIZE, DEFAULT_MAX_BLOCK_SIZE)); 276 } 277 278 public LruBlockCache(long maxSize, long blockSize, Configuration conf) { 279 this(maxSize, blockSize, true, conf); 280 } 281 282 /** 283 * Configurable constructor. Use this constructor if not using defaults. 284 * @param maxSize maximum size of this cache, in bytes 285 * @param blockSize expected average size of blocks, in bytes 286 * @param evictionThread whether to run evictions in a bg thread or not 287 * @param mapInitialSize initial size of backing ConcurrentHashMap 288 * @param mapLoadFactor initial load factor of backing ConcurrentHashMap 289 * @param mapConcurrencyLevel initial concurrency factor for backing CHM 290 * @param minFactor percentage of total size that eviction will evict until 291 * @param acceptableFactor percentage of total size that triggers eviction 292 * @param singleFactor percentage of total size for single-access blocks 293 * @param multiFactor percentage of total size for multiple-access blocks 294 * @param memoryFactor percentage of total size for in-memory blocks 295 */ 296 public LruBlockCache(long maxSize, long blockSize, boolean evictionThread, int mapInitialSize, 297 float mapLoadFactor, int mapConcurrencyLevel, float minFactor, float acceptableFactor, 298 float singleFactor, float multiFactor, float memoryFactor, float hardLimitFactor, 299 boolean forceInMemory, long maxBlockSize) { 300 this.maxBlockSize = maxBlockSize; 301 if ( 302 singleFactor + multiFactor + memoryFactor != 1 || singleFactor < 0 || multiFactor < 0 303 || memoryFactor < 0 304 ) { 305 throw new IllegalArgumentException( 306 "Single, multi, and memory factors " + " should be non-negative and total 1.0"); 307 } 308 if (minFactor >= acceptableFactor) { 309 throw new IllegalArgumentException("minFactor must be smaller than acceptableFactor"); 310 } 311 if (minFactor >= 1.0f || acceptableFactor >= 1.0f) { 312 throw new IllegalArgumentException("all factors must be < 1"); 313 } 314 this.maxSize = maxSize; 315 this.blockSize = blockSize; 316 this.forceInMemory = forceInMemory; 317 map = new ConcurrentHashMap<>(mapInitialSize, mapLoadFactor, mapConcurrencyLevel); 318 this.minFactor = minFactor; 319 this.acceptableFactor = acceptableFactor; 320 this.singleFactor = singleFactor; 321 this.multiFactor = multiFactor; 322 this.memoryFactor = memoryFactor; 323 this.stats = new CacheStats(this.getClass().getSimpleName()); 324 this.count = new AtomicLong(0); 325 this.elements = new AtomicLong(0); 326 this.overhead = calculateOverhead(maxSize, blockSize, mapConcurrencyLevel); 327 this.size = new AtomicLong(this.overhead); 328 this.hardCapacityLimitFactor = hardLimitFactor; 329 if (evictionThread) { 330 this.evictionThread = new EvictionThread(this); 331 this.evictionThread.start(); // FindBugs SC_START_IN_CTOR 332 } else { 333 this.evictionThread = null; 334 } 335 // TODO: Add means of turning this off. Bit obnoxious running thread just to make a log 336 // every five minutes. 337 this.scheduleThreadPool.scheduleAtFixedRate(new StatisticsThread(this), STAT_THREAD_PERIOD, 338 STAT_THREAD_PERIOD, TimeUnit.SECONDS); 339 } 340 341 @Override 342 public void setVictimCache(BlockCache victimCache) { 343 if (victimHandler != null) { 344 throw new IllegalArgumentException("The victim cache has already been set"); 345 } 346 victimHandler = requireNonNull(victimCache); 347 } 348 349 @Override 350 public void setMaxSize(long maxSize) { 351 this.maxSize = maxSize; 352 if (this.size.get() > acceptableSize() && !evictionInProgress) { 353 runEviction(); 354 } 355 } 356 357 /** 358 * The block cached in LRUBlockCache will always be an heap block: on the one side, the heap 359 * access will be more faster then off-heap, the small index block or meta block cached in 360 * CombinedBlockCache will benefit a lot. on other side, the LRUBlockCache size is always 361 * calculated based on the total heap size, if caching an off-heap block in LRUBlockCache, the 362 * heap size will be messed up. Here we will clone the block into an heap block if it's an 363 * off-heap block, otherwise just use the original block. The key point is maintain the refCnt of 364 * the block (HBASE-22127): <br> 365 * 1. if cache the cloned heap block, its refCnt is an totally new one, it's easy to handle; <br> 366 * 2. if cache the original heap block, we're sure that it won't be tracked in ByteBuffAllocator's 367 * reservoir, if both RPC and LRUBlockCache release the block, then it can be garbage collected by 368 * JVM, so need a retain here. 369 * @param buf the original block 370 * @return an block with an heap memory backend. 371 */ 372 private Cacheable asReferencedHeapBlock(Cacheable buf) { 373 if (buf instanceof HFileBlock) { 374 HFileBlock blk = ((HFileBlock) buf); 375 if (blk.isSharedMem()) { 376 return HFileBlock.deepCloneOnHeap(blk); 377 } 378 } 379 // The block will be referenced by this LRUBlockCache, so should increase its refCnt here. 380 return buf.retain(); 381 } 382 383 // BlockCache implementation 384 385 /** 386 * Cache the block with the specified name and buffer. 387 * <p> 388 * It is assumed this will NOT be called on an already cached block. In rare cases (HBASE-8547) 389 * this can happen, for which we compare the buffer contents. 390 * @param cacheKey block's cache key 391 * @param buf block buffer 392 * @param inMemory if block is in-memory 393 */ 394 @Override 395 public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory) { 396 if (buf.heapSize() > maxBlockSize) { 397 // If there are a lot of blocks that are too 398 // big this can make the logs way too noisy. 399 // So we log 2% 400 if (stats.failInsert() % 50 == 0) { 401 LOG.warn("Trying to cache too large a block " + cacheKey.getHfileName() + " @ " 402 + cacheKey.getOffset() + " is " + buf.heapSize() + " which is larger than " 403 + maxBlockSize); 404 } 405 return; 406 } 407 408 LruCachedBlock cb = map.get(cacheKey); 409 if (cb != null && !BlockCacheUtil.shouldReplaceExistingCacheBlock(this, cacheKey, buf)) { 410 return; 411 } 412 long currentSize = size.get(); 413 long currentAcceptableSize = acceptableSize(); 414 long hardLimitSize = (long) (hardCapacityLimitFactor * currentAcceptableSize); 415 if (currentSize >= hardLimitSize) { 416 stats.failInsert(); 417 if (LOG.isTraceEnabled()) { 418 LOG.trace("LruBlockCache current size " + StringUtils.byteDesc(currentSize) 419 + " has exceeded acceptable size " + StringUtils.byteDesc(currentAcceptableSize) + "." 420 + " The hard limit size is " + StringUtils.byteDesc(hardLimitSize) 421 + ", failed to put cacheKey:" + cacheKey + " into LruBlockCache."); 422 } 423 if (!evictionInProgress) { 424 runEviction(); 425 } 426 return; 427 } 428 // Ensure that the block is an heap one. 429 buf = asReferencedHeapBlock(buf); 430 cb = new LruCachedBlock(cacheKey, buf, count.incrementAndGet(), inMemory); 431 long newSize = updateSizeMetrics(cb, false); 432 LruCachedBlock previous = map.put(cacheKey, cb); 433 if (previous != null) { 434 // We replaced an existing block (see BlockCacheUtil#shouldReplaceExistingCacheBlock), so 435 // take the replaced block out of the size and element counters, otherwise it is counted 436 // forever and the cache fills up with blocks it no longer holds. 437 newSize = updateSizeMetrics(previous, true); 438 elements.decrementAndGet(); 439 BlockType previousType = previous.getBuffer().getBlockType(); 440 if (previousType.isBloom()) { 441 bloomBlockElements.decrement(); 442 } else if (previousType.isIndex()) { 443 indexBlockElements.decrement(); 444 } else if (previousType.isData()) { 445 dataBlockElements.decrement(); 446 } 447 // The cache no longer references the replaced block. 448 previous.getBuffer().release(); 449 } 450 long val = elements.incrementAndGet(); 451 if (buf.getBlockType().isBloom()) { 452 bloomBlockElements.increment(); 453 } else if (buf.getBlockType().isIndex()) { 454 indexBlockElements.increment(); 455 } else if (buf.getBlockType().isData()) { 456 dataBlockElements.increment(); 457 } 458 if (LOG.isTraceEnabled()) { 459 long size = map.size(); 460 assertCounterSanity(size, val); 461 } 462 if (newSize > currentAcceptableSize && !evictionInProgress) { 463 runEviction(); 464 } 465 } 466 467 /** 468 * Sanity-checking for parity between actual block cache content and metrics. Intended only for 469 * use with TRACE level logging and -ea JVM. 470 */ 471 private static void assertCounterSanity(long mapSize, long counterVal) { 472 if (counterVal < 0) { 473 LOG.trace("counterVal overflow. Assertions unreliable. counterVal=" + counterVal 474 + ", mapSize=" + mapSize); 475 return; 476 } 477 if (mapSize < Integer.MAX_VALUE) { 478 double pct_diff = Math.abs((((double) counterVal) / ((double) mapSize)) - 1.); 479 if (pct_diff > 0.05) { 480 LOG.trace("delta between reported and actual size > 5%. counterVal=" + counterVal 481 + ", mapSize=" + mapSize); 482 } 483 } 484 } 485 486 /** 487 * Cache the block with the specified name and buffer. 488 * <p> 489 * TODO after HBASE-22005, we may cache an block which allocated from off-heap, but our LRU cache 490 * sizing is based on heap size, so we should handle this in HBASE-22127. It will introduce an 491 * switch whether make the LRU on-heap or not, if so we may need copy the memory to on-heap, 492 * otherwise the caching size is based on off-heap. 493 * @param cacheKey block's cache key 494 * @param buf block buffer 495 */ 496 @Override 497 public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) { 498 cacheBlock(cacheKey, buf, false); 499 } 500 501 /** 502 * Helper function that updates the local size counter and also updates any per-cf or 503 * per-blocktype metrics it can discern from given {@link LruCachedBlock} 504 */ 505 private long updateSizeMetrics(LruCachedBlock cb, boolean evict) { 506 long heapsize = cb.heapSize(); 507 BlockType bt = cb.getBuffer().getBlockType(); 508 if (evict) { 509 heapsize *= -1; 510 } 511 if (bt != null) { 512 if (bt.isBloom()) { 513 bloomBlockSize.add(heapsize); 514 } else if (bt.isIndex()) { 515 indexBlockSize.add(heapsize); 516 } else if (bt.isData()) { 517 dataBlockSize.add(heapsize); 518 } 519 } 520 return size.addAndGet(heapsize); 521 } 522 523 /** 524 * Get the buffer of the block with the specified name. 525 * @param cacheKey block's cache key 526 * @param caching true if the caller caches blocks on cache misses 527 * @param repeat Whether this is a repeat lookup for the same block (used to avoid 528 * double counting cache misses when doing double-check locking) 529 * @param updateCacheMetrics Whether to update cache metrics or not 530 * @return buffer of specified cache key, or null if not in cache 531 */ 532 @Override 533 public Cacheable getBlock(BlockCacheKey cacheKey, boolean caching, boolean repeat, 534 boolean updateCacheMetrics) { 535 // Note: 'map' must be a ConcurrentHashMap or the supplier may be invoked more than once. 536 LruCachedBlock cb = map.computeIfPresent(cacheKey, (key, val) -> { 537 // It will be referenced by RPC path, so increase here. NOTICE: Must do the retain inside 538 // this block. because if retain outside the map#computeIfPresent, the evictBlock may remove 539 // the block and release, then we're retaining a block with refCnt=0 which is disallowed. 540 // see HBASE-22422. 541 val.getBuffer().retain(); 542 return val; 543 }); 544 if (cb == null) { 545 if (!repeat && updateCacheMetrics) { 546 stats.miss(caching, cacheKey.isPrimary(), cacheKey.getBlockType()); 547 } 548 // If there is another block cache then try and read there. 549 // However if this is a retry ( second time in double checked locking ) 550 // And it's already a miss then the l2 will also be a miss. 551 if (victimHandler != null && !repeat) { 552 // The handler will increase result's refCnt for RPC, so need no extra retain. 553 Cacheable result = victimHandler.getBlock(cacheKey, caching, repeat, updateCacheMetrics); 554 // Promote this to L1. 555 if (result != null) { 556 if (caching) { 557 cacheBlock(cacheKey, result, /* inMemory = */ false); 558 } 559 } 560 return result; 561 } 562 return null; 563 } 564 if (updateCacheMetrics) { 565 stats.hit(caching, cacheKey.isPrimary(), cacheKey.getBlockType()); 566 } 567 cb.access(count.incrementAndGet()); 568 return cb.getBuffer(); 569 } 570 571 /** 572 * Whether the cache contains block with specified cacheKey 573 * @return true if contains the block 574 */ 575 @Override 576 public boolean containsBlock(BlockCacheKey cacheKey) { 577 return map.containsKey(cacheKey); 578 } 579 580 @Override 581 public boolean evictBlock(BlockCacheKey cacheKey) { 582 LruCachedBlock cb = map.get(cacheKey); 583 return cb != null && evictBlock(cb, false) > 0; 584 } 585 586 /** 587 * Evicts all blocks for a specific HFile. This is an expensive operation implemented as a 588 * linear-time search through all blocks in the cache. Ideally this should be a search in a 589 * log-access-time map. 590 * <p> 591 * This is used for evict-on-close to remove all blocks of a specific HFile. 592 * @return the number of blocks evicted 593 */ 594 @Override 595 public int evictBlocksByHfileName(String hfileName) { 596 int numEvicted = 0; 597 for (BlockCacheKey key : map.keySet()) { 598 if (key.getHfileName().equals(hfileName)) { 599 if (evictBlock(key)) { 600 ++numEvicted; 601 } 602 } 603 } 604 if (victimHandler != null) { 605 numEvicted += victimHandler.evictBlocksByHfileName(hfileName); 606 } 607 return numEvicted; 608 } 609 610 /** 611 * Evict the block, and it will be cached by the victim handler if exists && block may be 612 * read again later 613 * @param evictedByEvictionProcess true if the given block is evicted by EvictionThread 614 * @return the heap size of evicted block 615 */ 616 protected long evictBlock(LruCachedBlock block, boolean evictedByEvictionProcess) { 617 // The block actually removed from the map. It can differ from the passed block if the same key 618 // was replaced in the meantime (see BlockCacheUtil#shouldReplaceExistingCacheBlock), so all 619 // the accounting below must use the removed block, not the passed one. 620 final MutableObject<LruCachedBlock> removed = new MutableObject<>(); 621 // Note: 'map' must be a ConcurrentHashMap or the supplier may be invoked more than once. 622 map.computeIfPresent(block.getCacheKey(), (k, v) -> { 623 // Run the victim handler before we remove the mapping in the L1 map. It must complete 624 // quickly because other removal or insertion operations can be blocked in the meantime. 625 if (evictedByEvictionProcess && victimHandler != null) { 626 victimHandler.cacheBlock(k, v.getBuffer()); 627 } 628 // Decrease the block's reference count, and if refCount is 0, then it'll auto-deallocate. DO 629 // NOT move this up because if we do that then the victimHandler may access the buffer with 630 // refCnt = 0 which is disallowed. 631 v.getBuffer().release(); 632 removed.setValue(v); 633 // By returning null from the supplier we remove the mapping from the L1 map. 634 return null; 635 }); 636 LruCachedBlock evicted = removed.getValue(); 637 // If we didn't find anything to evict there is nothing more to do here. 638 if (evicted == null) { 639 return 0; 640 } 641 // We evicted the block so update L1 statistics. 642 updateSizeMetrics(evicted, true); 643 long val = elements.decrementAndGet(); 644 if (LOG.isTraceEnabled()) { 645 long size = map.size(); 646 assertCounterSanity(size, val); 647 } 648 BlockType bt = evicted.getBuffer().getBlockType(); 649 if (bt.isBloom()) { 650 bloomBlockElements.decrement(); 651 } else if (bt.isIndex()) { 652 indexBlockElements.decrement(); 653 } else if (bt.isData()) { 654 dataBlockElements.decrement(); 655 } 656 if (evictedByEvictionProcess) { 657 // When the eviction of the block happened because of invalidation of HFiles, no need to 658 // update the stats counter. 659 stats.evicted(evicted.getCachedTime(), evicted.getCacheKey().isPrimary()); 660 } 661 return evicted.heapSize(); 662 } 663 664 /** 665 * Multi-threaded call to run the eviction process. 666 */ 667 private void runEviction() { 668 if (evictionThread == null || !evictionThread.isGo()) { 669 evict(); 670 } else { 671 evictionThread.evict(); 672 } 673 } 674 675 boolean isEvictionInProgress() { 676 return evictionInProgress; 677 } 678 679 long getOverhead() { 680 return overhead; 681 } 682 683 /** 684 * Eviction method. 685 */ 686 void evict() { 687 688 // Ensure only one eviction at a time 689 if (!evictionLock.tryLock()) { 690 return; 691 } 692 693 try { 694 evictionInProgress = true; 695 long currentSize = this.size.get(); 696 long bytesToFree = currentSize - minSize(); 697 698 if (LOG.isTraceEnabled()) { 699 LOG.trace("Block cache LRU eviction started; Attempting to free " 700 + StringUtils.byteDesc(bytesToFree) + " of total=" + StringUtils.byteDesc(currentSize)); 701 } 702 703 if (bytesToFree <= 0) { 704 return; 705 } 706 707 // Instantiate priority buckets 708 BlockBucket bucketSingle = new BlockBucket("single", bytesToFree, blockSize, singleSize()); 709 BlockBucket bucketMulti = new BlockBucket("multi", bytesToFree, blockSize, multiSize()); 710 BlockBucket bucketMemory = new BlockBucket("memory", bytesToFree, blockSize, memorySize()); 711 712 // Scan entire map putting into appropriate buckets 713 for (LruCachedBlock cachedBlock : map.values()) { 714 switch (cachedBlock.getPriority()) { 715 case SINGLE: { 716 bucketSingle.add(cachedBlock); 717 break; 718 } 719 case MULTI: { 720 bucketMulti.add(cachedBlock); 721 break; 722 } 723 case MEMORY: { 724 bucketMemory.add(cachedBlock); 725 break; 726 } 727 } 728 } 729 730 long bytesFreed = 0; 731 if (forceInMemory || memoryFactor > 0.999f) { 732 long s = bucketSingle.totalSize(); 733 long m = bucketMulti.totalSize(); 734 if (bytesToFree > (s + m)) { 735 // this means we need to evict blocks in memory bucket to make room, 736 // so the single and multi buckets will be emptied 737 bytesFreed = bucketSingle.free(s); 738 bytesFreed += bucketMulti.free(m); 739 if (LOG.isTraceEnabled()) { 740 LOG.trace( 741 "freed " + StringUtils.byteDesc(bytesFreed) + " from single and multi buckets"); 742 } 743 bytesFreed += bucketMemory.free(bytesToFree - bytesFreed); 744 if (LOG.isTraceEnabled()) { 745 LOG.trace( 746 "freed " + StringUtils.byteDesc(bytesFreed) + " total from all three buckets "); 747 } 748 } else { 749 // this means no need to evict block in memory bucket, 750 // and we try best to make the ratio between single-bucket and 751 // multi-bucket is 1:2 752 long bytesRemain = s + m - bytesToFree; 753 if (3 * s <= bytesRemain) { 754 // single-bucket is small enough that no eviction happens for it 755 // hence all eviction goes from multi-bucket 756 bytesFreed = bucketMulti.free(bytesToFree); 757 } else if (3 * m <= 2 * bytesRemain) { 758 // multi-bucket is small enough that no eviction happens for it 759 // hence all eviction goes from single-bucket 760 bytesFreed = bucketSingle.free(bytesToFree); 761 } else { 762 // both buckets need to evict some blocks 763 bytesFreed = bucketSingle.free(s - bytesRemain / 3); 764 if (bytesFreed < bytesToFree) { 765 bytesFreed += bucketMulti.free(bytesToFree - bytesFreed); 766 } 767 } 768 } 769 } else { 770 PriorityQueue<BlockBucket> bucketQueue = new PriorityQueue<>(3); 771 772 bucketQueue.add(bucketSingle); 773 bucketQueue.add(bucketMulti); 774 bucketQueue.add(bucketMemory); 775 776 int remainingBuckets = bucketQueue.size(); 777 778 BlockBucket bucket; 779 while ((bucket = bucketQueue.poll()) != null) { 780 long overflow = bucket.overflow(); 781 if (overflow > 0) { 782 long bucketBytesToFree = 783 Math.min(overflow, (bytesToFree - bytesFreed) / remainingBuckets); 784 bytesFreed += bucket.free(bucketBytesToFree); 785 } 786 remainingBuckets--; 787 } 788 } 789 if (LOG.isTraceEnabled()) { 790 long single = bucketSingle.totalSize(); 791 long multi = bucketMulti.totalSize(); 792 long memory = bucketMemory.totalSize(); 793 LOG.trace( 794 "Block cache LRU eviction completed; " + "freed=" + StringUtils.byteDesc(bytesFreed) 795 + ", " + "total=" + StringUtils.byteDesc(this.size.get()) + ", " + "single=" 796 + StringUtils.byteDesc(single) + ", " + "multi=" + StringUtils.byteDesc(multi) + ", " 797 + "memory=" + StringUtils.byteDesc(memory)); 798 } 799 } finally { 800 stats.evict(); 801 evictionInProgress = false; 802 evictionLock.unlock(); 803 } 804 } 805 806 @Override 807 public String toString() { 808 return MoreObjects.toStringHelper(this).add("blockCount", getBlockCount()) 809 .add("currentSize", StringUtils.byteDesc(getCurrentSize())) 810 .add("freeSize", StringUtils.byteDesc(getFreeSize())) 811 .add("maxSize", StringUtils.byteDesc(getMaxSize())) 812 .add("heapSize", StringUtils.byteDesc(heapSize())) 813 .add("minSize", StringUtils.byteDesc(minSize())).add("minFactor", minFactor) 814 .add("multiSize", StringUtils.byteDesc(multiSize())).add("multiFactor", multiFactor) 815 .add("singleSize", StringUtils.byteDesc(singleSize())).add("singleFactor", singleFactor) 816 .toString(); 817 } 818 819 /** 820 * Used to group blocks into priority buckets. There will be a BlockBucket for each priority 821 * (single, multi, memory). Once bucketed, the eviction algorithm takes the appropriate number of 822 * elements out of each according to configuration parameters and their relatives sizes. 823 */ 824 private class BlockBucket implements Comparable<BlockBucket> { 825 826 private final String name; 827 private LruCachedBlockQueue queue; 828 private long totalSize = 0; 829 private long bucketSize; 830 831 public BlockBucket(String name, long bytesToFree, long blockSize, long bucketSize) { 832 this.name = name; 833 this.bucketSize = bucketSize; 834 queue = new LruCachedBlockQueue(bytesToFree, blockSize); 835 totalSize = 0; 836 } 837 838 public void add(LruCachedBlock block) { 839 totalSize += block.heapSize(); 840 queue.add(block); 841 } 842 843 public long free(long toFree) { 844 if (LOG.isTraceEnabled()) { 845 LOG.trace("freeing " + StringUtils.byteDesc(toFree) + " from " + this); 846 } 847 LruCachedBlock cb; 848 long freedBytes = 0; 849 while ((cb = queue.pollLast()) != null) { 850 freedBytes += evictBlock(cb, true); 851 if (freedBytes >= toFree) { 852 return freedBytes; 853 } 854 } 855 if (LOG.isTraceEnabled()) { 856 LOG.trace("freed " + StringUtils.byteDesc(freedBytes) + " from " + this); 857 } 858 return freedBytes; 859 } 860 861 public long overflow() { 862 return totalSize - bucketSize; 863 } 864 865 public long totalSize() { 866 return totalSize; 867 } 868 869 @Override 870 public int compareTo(BlockBucket that) { 871 return Long.compare(this.overflow(), that.overflow()); 872 } 873 874 @Override 875 public boolean equals(Object that) { 876 if (that == null || !(that instanceof BlockBucket)) { 877 return false; 878 } 879 return compareTo((BlockBucket) that) == 0; 880 } 881 882 @Override 883 public int hashCode() { 884 return Objects.hashCode(name, bucketSize, queue, totalSize); 885 } 886 887 @Override 888 public String toString() { 889 return MoreObjects.toStringHelper(this).add("name", name) 890 .add("totalSize", StringUtils.byteDesc(totalSize)) 891 .add("bucketSize", StringUtils.byteDesc(bucketSize)).toString(); 892 } 893 } 894 895 /** 896 * Get the maximum size of this cache. 897 * @return max size in bytes 898 */ 899 900 @Override 901 public long getMaxSize() { 902 return this.maxSize; 903 } 904 905 @Override 906 public long getCurrentSize() { 907 return this.size.get(); 908 } 909 910 @Override 911 public long getCurrentDataSize() { 912 return this.dataBlockSize.sum(); 913 } 914 915 public long getCurrentIndexSize() { 916 return this.indexBlockSize.sum(); 917 } 918 919 public long getCurrentBloomSize() { 920 return this.bloomBlockSize.sum(); 921 } 922 923 @Override 924 public long getFreeSize() { 925 return getMaxSize() - getCurrentSize(); 926 } 927 928 @Override 929 public long size() { 930 return getMaxSize(); 931 } 932 933 @Override 934 public long getBlockCount() { 935 return this.elements.get(); 936 } 937 938 @Override 939 public long getDataBlockCount() { 940 return this.dataBlockElements.sum(); 941 } 942 943 public long getIndexBlockCount() { 944 return this.indexBlockElements.sum(); 945 } 946 947 public long getBloomBlockCount() { 948 return this.bloomBlockElements.sum(); 949 } 950 951 EvictionThread getEvictionThread() { 952 return this.evictionThread; 953 } 954 955 /* 956 * Eviction thread. Sits in waiting state until an eviction is triggered when the cache size grows 957 * above the acceptable level.<p> Thread is triggered into action by {@link 958 * LruBlockCache#runEviction()} 959 */ 960 static class EvictionThread extends Thread { 961 962 private WeakReference<LruBlockCache> cache; 963 private volatile boolean go = true; 964 // flag set after enter the run method, used for test 965 private boolean enteringRun = false; 966 967 public EvictionThread(LruBlockCache cache) { 968 super(Thread.currentThread().getName() + ".LruBlockCache.EvictionThread"); 969 setDaemon(true); 970 this.cache = new WeakReference<>(cache); 971 } 972 973 @Override 974 public void run() { 975 enteringRun = true; 976 while (this.go) { 977 synchronized (this) { 978 try { 979 this.wait(1000 * 10/* Don't wait for ever */); 980 } catch (InterruptedException e) { 981 LOG.warn("Interrupted eviction thread ", e); 982 Thread.currentThread().interrupt(); 983 } 984 } 985 LruBlockCache cache = this.cache.get(); 986 if (cache == null) { 987 this.go = false; 988 break; 989 } 990 cache.evict(); 991 } 992 } 993 994 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NN_NAKED_NOTIFY", 995 justification = "This is what we want") 996 public void evict() { 997 synchronized (this) { 998 this.notifyAll(); 999 } 1000 } 1001 1002 synchronized void shutdown() { 1003 this.go = false; 1004 this.notifyAll(); 1005 } 1006 1007 public boolean isGo() { 1008 return go; 1009 } 1010 1011 /** 1012 * Used for the test. 1013 */ 1014 boolean isEnteringRun() { 1015 return this.enteringRun; 1016 } 1017 } 1018 1019 /* 1020 * Statistics thread. Periodically prints the cache statistics to the log. 1021 */ 1022 static class StatisticsThread extends Thread { 1023 1024 private final LruBlockCache lru; 1025 1026 public StatisticsThread(LruBlockCache lru) { 1027 super("LruBlockCacheStats"); 1028 setDaemon(true); 1029 this.lru = lru; 1030 } 1031 1032 @Override 1033 public void run() { 1034 lru.logStats(); 1035 } 1036 } 1037 1038 public void logStats() { 1039 // Log size 1040 long usedSize = heapSize(); 1041 long freeSize = maxSize - usedSize; 1042 LruBlockCache.LOG.info("totalSize=" + StringUtils.byteDesc(maxSize) + ", " + "usedSize=" 1043 + StringUtils.byteDesc(usedSize) + ", " + "freeSize=" + StringUtils.byteDesc(freeSize) + ", " 1044 + "max=" + StringUtils.byteDesc(this.maxSize) + ", " + "blockCount=" + getBlockCount() + ", " 1045 + "accesses=" + stats.getRequestCount() + ", " + "hits=" + stats.getHitCount() + ", " 1046 + "hitRatio=" 1047 + (stats.getHitCount() == 0 1048 ? "0" 1049 : (StringUtils.formatPercent(stats.getHitRatio(), 2) + ", ")) 1050 + ", " + "cachingAccesses=" + stats.getRequestCachingCount() + ", " + "cachingHits=" 1051 + stats.getHitCachingCount() + ", " + "cachingHitsRatio=" 1052 + (stats.getHitCachingCount() == 0 1053 ? "0," 1054 : (StringUtils.formatPercent(stats.getHitCachingRatio(), 2) + ", ")) 1055 + "evictions=" + stats.getEvictionCount() + ", " + "evicted=" + stats.getEvictedCount() + ", " 1056 + "evictedPerRun=" + stats.evictedPerEviction()); 1057 } 1058 1059 /** 1060 * Get counter statistics for this cache. 1061 * <p> 1062 * Includes: total accesses, hits, misses, evicted blocks, and runs of the eviction processes. 1063 */ 1064 @Override 1065 public CacheStats getStats() { 1066 return this.stats; 1067 } 1068 1069 public final static long CACHE_FIXED_OVERHEAD = 1070 ClassSize.estimateBase(LruBlockCache.class, false); 1071 1072 @Override 1073 public long heapSize() { 1074 return getCurrentSize(); 1075 } 1076 1077 private static long calculateOverhead(long maxSize, long blockSize, int concurrency) { 1078 // FindBugs ICAST_INTEGER_MULTIPLY_CAST_TO_LONG 1079 return CACHE_FIXED_OVERHEAD + ClassSize.CONCURRENT_HASHMAP 1080 + ((long) Math.ceil(maxSize * 1.2 / blockSize) * ClassSize.CONCURRENT_HASHMAP_ENTRY) 1081 + ((long) concurrency * ClassSize.CONCURRENT_HASHMAP_SEGMENT); 1082 } 1083 1084 @Override 1085 public Iterator<CachedBlock> iterator() { 1086 final Iterator<LruCachedBlock> iterator = map.values().iterator(); 1087 1088 return new Iterator<CachedBlock>() { 1089 private final long now = System.nanoTime(); 1090 1091 @Override 1092 public boolean hasNext() { 1093 return iterator.hasNext(); 1094 } 1095 1096 @Override 1097 public CachedBlock next() { 1098 final LruCachedBlock b = iterator.next(); 1099 return new CachedBlock() { 1100 @Override 1101 public String toString() { 1102 return BlockCacheUtil.toString(this, now); 1103 } 1104 1105 @Override 1106 public BlockPriority getBlockPriority() { 1107 return b.getPriority(); 1108 } 1109 1110 @Override 1111 public BlockType getBlockType() { 1112 return b.getBuffer().getBlockType(); 1113 } 1114 1115 @Override 1116 public long getOffset() { 1117 return b.getCacheKey().getOffset(); 1118 } 1119 1120 @Override 1121 public long getSize() { 1122 return b.getBuffer().heapSize(); 1123 } 1124 1125 @Override 1126 public long getCachedTime() { 1127 return b.getCachedTime(); 1128 } 1129 1130 @Override 1131 public String getFilename() { 1132 return b.getCacheKey().getHfileName(); 1133 } 1134 1135 @Override 1136 public int compareTo(CachedBlock other) { 1137 int diff = this.getFilename().compareTo(other.getFilename()); 1138 if (diff != 0) { 1139 return diff; 1140 } 1141 diff = Long.compare(this.getOffset(), other.getOffset()); 1142 if (diff != 0) { 1143 return diff; 1144 } 1145 if (other.getCachedTime() < 0 || this.getCachedTime() < 0) { 1146 throw new IllegalStateException(this.getCachedTime() + ", " + other.getCachedTime()); 1147 } 1148 return Long.compare(other.getCachedTime(), this.getCachedTime()); 1149 } 1150 1151 @Override 1152 public int hashCode() { 1153 return b.hashCode(); 1154 } 1155 1156 @Override 1157 public boolean equals(Object obj) { 1158 if (obj instanceof CachedBlock) { 1159 CachedBlock cb = (CachedBlock) obj; 1160 return compareTo(cb) == 0; 1161 } else { 1162 return false; 1163 } 1164 } 1165 }; 1166 } 1167 1168 @Override 1169 public void remove() { 1170 throw new UnsupportedOperationException(); 1171 } 1172 }; 1173 } 1174 1175 // Simple calculators of sizes given factors and maxSize 1176 @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.UNITTEST) 1177 public long acceptableSize() { 1178 return (long) Math.floor(this.maxSize * this.acceptableFactor); 1179 } 1180 1181 private long minSize() { 1182 return (long) Math.floor(this.maxSize * this.minFactor); 1183 } 1184 1185 private long singleSize() { 1186 return (long) Math.floor(this.maxSize * this.singleFactor * this.minFactor); 1187 } 1188 1189 private long multiSize() { 1190 return (long) Math.floor(this.maxSize * this.multiFactor * this.minFactor); 1191 } 1192 1193 private long memorySize() { 1194 return (long) Math.floor(this.maxSize * this.memoryFactor * this.minFactor); 1195 } 1196 1197 @Override 1198 public void shutdown() { 1199 if (victimHandler != null) { 1200 victimHandler.shutdown(); 1201 } 1202 this.scheduleThreadPool.shutdown(); 1203 for (int i = 0; i < 10; i++) { 1204 if (!this.scheduleThreadPool.isShutdown()) { 1205 try { 1206 Thread.sleep(10); 1207 } catch (InterruptedException e) { 1208 LOG.warn("Interrupted while sleeping"); 1209 Thread.currentThread().interrupt(); 1210 break; 1211 } 1212 } 1213 } 1214 1215 if (!this.scheduleThreadPool.isShutdown()) { 1216 List<Runnable> runnables = this.scheduleThreadPool.shutdownNow(); 1217 LOG.debug("Still running " + runnables); 1218 } 1219 this.evictionThread.shutdown(); 1220 } 1221 1222 /** Clears the cache. Used in tests. */ 1223 public void clearCache() { 1224 this.map.clear(); 1225 this.elements.set(0); 1226 } 1227 1228 /** 1229 * Used in testing. May be very inefficient. 1230 * @return the set of cached file names 1231 */ 1232 SortedSet<String> getCachedFileNamesForTest() { 1233 SortedSet<String> fileNames = new TreeSet<>(); 1234 for (BlockCacheKey cacheKey : map.keySet()) { 1235 fileNames.add(cacheKey.getHfileName()); 1236 } 1237 return fileNames; 1238 } 1239 1240 public Map<DataBlockEncoding, Integer> getEncodingCountsForTest() { 1241 Map<DataBlockEncoding, Integer> counts = new EnumMap<>(DataBlockEncoding.class); 1242 for (LruCachedBlock block : map.values()) { 1243 DataBlockEncoding encoding = ((HFileBlock) block.getBuffer()).getDataBlockEncoding(); 1244 Integer count = counts.get(encoding); 1245 counts.put(encoding, (count == null ? 0 : count) + 1); 1246 } 1247 return counts; 1248 } 1249 1250 Map<BlockCacheKey, LruCachedBlock> getMapForTests() { 1251 return map; 1252 } 1253 1254 @Override 1255 public BlockCache[] getBlockCaches() { 1256 if (victimHandler != null) { 1257 return new BlockCache[] { this, this.victimHandler }; 1258 } 1259 return null; 1260 } 1261}