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 org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNotNull;
022import static org.junit.Assert.assertNull;
023import static org.junit.Assert.assertTrue;
024
025import java.nio.ByteBuffer;
026import java.util.Random;
027import java.util.concurrent.ExecutorService;
028import java.util.concurrent.Executors;
029import java.util.concurrent.TimeUnit;
030import java.util.concurrent.atomic.AtomicInteger;
031import org.apache.hadoop.conf.Configuration;
032import org.apache.hadoop.hbase.HBaseClassTestRule;
033import org.apache.hadoop.hbase.HBaseConfiguration;
034import org.apache.hadoop.hbase.Waiter;
035import org.apache.hadoop.hbase.Waiter.ExplainingPredicate;
036import org.apache.hadoop.hbase.io.HeapSize;
037import org.apache.hadoop.hbase.io.hfile.LruBlockCache.EvictionThread;
038import org.apache.hadoop.hbase.testclassification.IOTests;
039import org.apache.hadoop.hbase.testclassification.SmallTests;
040import org.apache.hadoop.hbase.util.ClassSize;
041import org.junit.ClassRule;
042import org.junit.Test;
043import org.junit.experimental.categories.Category;
044
045/**
046 * Tests the concurrent LruBlockCache.<p>
047 *
048 * Tests will ensure it grows and shrinks in size properly,
049 * evictions run when they're supposed to and do what they should,
050 * and that cached blocks are accessible when expected to be.
051 */
052@Category({IOTests.class, SmallTests.class})
053public class TestLruBlockCache {
054
055  @ClassRule
056  public static final HBaseClassTestRule CLASS_RULE =
057      HBaseClassTestRule.forClass(TestLruBlockCache.class);
058
059  @Test
060  public void testCacheEvictionThreadSafe() throws Exception {
061    long maxSize = 100000;
062    int numBlocks = 9;
063    int testRuns = 10;
064    final long blockSize = calculateBlockSizeDefault(maxSize, numBlocks);
065    assertTrue("calculateBlockSize appears broken.", blockSize * numBlocks <= maxSize);
066
067    final Configuration conf = HBaseConfiguration.create();
068    final LruBlockCache cache = new LruBlockCache(maxSize, blockSize);
069    EvictionThread evictionThread = cache.getEvictionThread();
070    assertTrue(evictionThread != null);
071    while (!evictionThread.isEnteringRun()) {
072      Thread.sleep(1);
073    }
074    final String hfileName = "hfile";
075    int threads = 10;
076    final int blocksPerThread = 5 * numBlocks;
077    for (int run = 0; run != testRuns; ++run) {
078      final AtomicInteger blockCount = new AtomicInteger(0);
079      ExecutorService service = Executors.newFixedThreadPool(threads);
080      for (int i = 0; i != threads; ++i) {
081        service.execute(new Runnable() {
082          @Override
083          public void run() {
084            for (int blockIndex = 0; blockIndex < blocksPerThread || (!cache.isEvictionInProgress()); ++blockIndex) {
085              CachedItem block = new CachedItem(hfileName, (int) blockSize, blockCount.getAndIncrement());
086              boolean inMemory = Math.random() > 0.5;
087              cache.cacheBlock(block.cacheKey, block, inMemory);
088            }
089            cache.evictBlocksByHfileName(hfileName);
090          }
091        });
092      }
093      service.shutdown();
094      // The test may fail here if the evict thread frees the blocks too fast
095      service.awaitTermination(10, TimeUnit.MINUTES);
096      Waiter.waitFor(conf, 10000, 100, new ExplainingPredicate<Exception>() {
097        @Override
098        public boolean evaluate() throws Exception {
099          return cache.getBlockCount() == 0;
100        }
101
102        @Override
103        public String explainFailure() throws Exception {
104          return "Cache block count failed to return to 0";
105        }
106      });
107      assertEquals(0, cache.getBlockCount());
108      assertEquals(cache.getOverhead(), cache.getCurrentSize());
109    }
110  }
111  @Test
112  public void testBackgroundEvictionThread() throws Exception {
113    long maxSize = 100000;
114    int numBlocks = 9;
115    long blockSize = calculateBlockSizeDefault(maxSize, numBlocks);
116    assertTrue("calculateBlockSize appears broken.", blockSize * numBlocks <= maxSize);
117
118    LruBlockCache cache = new LruBlockCache(maxSize,blockSize);
119    EvictionThread evictionThread = cache.getEvictionThread();
120    assertTrue(evictionThread != null);
121
122    CachedItem[] blocks = generateFixedBlocks(numBlocks + 1, blockSize, "block");
123
124    // Make sure eviction thread has entered run method
125    while (!evictionThread.isEnteringRun()) {
126      Thread.sleep(1);
127    }
128
129    // Add all the blocks
130    for (CachedItem block : blocks) {
131      cache.cacheBlock(block.cacheKey, block);
132    }
133
134    // wait until at least one eviction has run
135    int n = 0;
136    while(cache.getStats().getEvictionCount() == 0) {
137      Thread.sleep(200);
138      assertTrue("Eviction never happened.", n++ < 20);
139    }
140
141    // let cache stabilize
142    // On some systems, the cache will run multiple evictions before it attains
143    // steady-state. For instance, after populating the cache with 10 blocks,
144    // the first eviction evicts a single block and then a second eviction
145    // evicts another. I think this is due to the delta between minSize and
146    // acceptableSize, combined with variance between object overhead on
147    // different environments.
148    n = 0;
149    for (long prevCnt = 0 /* < number of blocks added */,
150              curCnt = cache.getBlockCount();
151        prevCnt != curCnt; prevCnt = curCnt, curCnt = cache.getBlockCount()) {
152      Thread.sleep(200);
153      assertTrue("Cache never stabilized.", n++ < 20);
154    }
155
156    long evictionCount = cache.getStats().getEvictionCount();
157    assertTrue(evictionCount >= 1);
158    System.out.println("Background Evictions run: " + evictionCount);
159  }
160
161  @Test
162  public void testCacheSimple() throws Exception {
163
164    long maxSize = 1000000;
165    long blockSize = calculateBlockSizeDefault(maxSize, 101);
166
167    LruBlockCache cache = new LruBlockCache(maxSize, blockSize);
168
169    CachedItem [] blocks = generateRandomBlocks(100, blockSize);
170
171    long expectedCacheSize = cache.heapSize();
172
173    // Confirm empty
174    for (CachedItem block : blocks) {
175      assertTrue(cache.getBlock(block.cacheKey, true, false, true) == null);
176    }
177
178    // Add blocks
179    for (CachedItem block : blocks) {
180      cache.cacheBlock(block.cacheKey, block);
181      expectedCacheSize += block.cacheBlockHeapSize();
182    }
183
184    // Verify correctly calculated cache heap size
185    assertEquals(expectedCacheSize, cache.heapSize());
186
187    // Check if all blocks are properly cached and retrieved
188    for (CachedItem block : blocks) {
189      HeapSize buf = cache.getBlock(block.cacheKey, true, false, true);
190      assertTrue(buf != null);
191      assertEquals(buf.heapSize(), block.heapSize());
192    }
193
194    // Re-add same blocks and ensure nothing has changed
195    long expectedBlockCount = cache.getBlockCount();
196    for (CachedItem block : blocks) {
197      cache.cacheBlock(block.cacheKey, block);
198    }
199    assertEquals(
200            "Cache should ignore cache requests for blocks already in cache",
201            expectedBlockCount, cache.getBlockCount());
202
203    // Verify correctly calculated cache heap size
204    assertEquals(expectedCacheSize, cache.heapSize());
205
206    // Check if all blocks are properly cached and retrieved
207    for (CachedItem block : blocks) {
208      HeapSize buf = cache.getBlock(block.cacheKey, true, false, true);
209      assertTrue(buf != null);
210      assertEquals(buf.heapSize(), block.heapSize());
211    }
212
213    // Expect no evictions
214    assertEquals(0, cache.getStats().getEvictionCount());
215    Thread t = new LruBlockCache.StatisticsThread(cache);
216    t.start();
217    t.join();
218  }
219
220  @Test
221  public void testCacheEvictionSimple() throws Exception {
222
223    long maxSize = 100000;
224    long blockSize = calculateBlockSizeDefault(maxSize, 10);
225
226    LruBlockCache cache = new LruBlockCache(maxSize,blockSize,false);
227
228    CachedItem [] blocks = generateFixedBlocks(10, blockSize, "block");
229
230    long expectedCacheSize = cache.heapSize();
231
232    // Add all the blocks
233    for (CachedItem block : blocks) {
234      cache.cacheBlock(block.cacheKey, block);
235      expectedCacheSize += block.cacheBlockHeapSize();
236    }
237
238    // A single eviction run should have occurred
239    assertEquals(1, cache.getStats().getEvictionCount());
240
241    // Our expected size overruns acceptable limit
242    assertTrue(expectedCacheSize >
243      (maxSize * LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
244
245    // But the cache did not grow beyond max
246    assertTrue(cache.heapSize() < maxSize);
247
248    // And is still below the acceptable limit
249    assertTrue(cache.heapSize() <
250        (maxSize * LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
251
252    // All blocks except block 0  should be in the cache
253    assertTrue(cache.getBlock(blocks[0].cacheKey, true, false, true) == null);
254    for(int i=1;i<blocks.length;i++) {
255      assertEquals(cache.getBlock(blocks[i].cacheKey, true, false, true),
256          blocks[i]);
257    }
258  }
259
260  @Test
261  public void testCacheEvictionTwoPriorities() throws Exception {
262
263    long maxSize = 100000;
264    long blockSize = calculateBlockSizeDefault(maxSize, 10);
265
266    LruBlockCache cache = new LruBlockCache(maxSize,blockSize,false);
267
268    CachedItem [] singleBlocks = generateFixedBlocks(5, 10000, "single");
269    CachedItem [] multiBlocks = generateFixedBlocks(5, 10000, "multi");
270
271    long expectedCacheSize = cache.heapSize();
272
273    // Add and get the multi blocks
274    for (CachedItem block : multiBlocks) {
275      cache.cacheBlock(block.cacheKey, block);
276      expectedCacheSize += block.cacheBlockHeapSize();
277      assertEquals(cache.getBlock(block.cacheKey, true, false, true), block);
278    }
279
280    // Add the single blocks (no get)
281    for (CachedItem block : singleBlocks) {
282      cache.cacheBlock(block.cacheKey, block);
283      expectedCacheSize += block.heapSize();
284    }
285
286    // A single eviction run should have occurred
287    assertEquals(1, cache.getStats().getEvictionCount());
288
289    // We expect two entries evicted
290    assertEquals(2, cache.getStats().getEvictedCount());
291
292    // Our expected size overruns acceptable limit
293    assertTrue(expectedCacheSize >
294      (maxSize * LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
295
296    // But the cache did not grow beyond max
297    assertTrue(cache.heapSize() <= maxSize);
298
299    // And is now below the acceptable limit
300    assertTrue(cache.heapSize() <=
301        (maxSize * LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
302
303    // We expect fairness across the two priorities.
304    // This test makes multi go barely over its limit, in-memory
305    // empty, and the rest in single.  Two single evictions and
306    // one multi eviction expected.
307    assertTrue(cache.getBlock(singleBlocks[0].cacheKey, true, false, true) == null);
308    assertTrue(cache.getBlock(multiBlocks[0].cacheKey, true, false, true) == null);
309
310    // And all others to be cached
311    for(int i=1;i<4;i++) {
312      assertEquals(cache.getBlock(singleBlocks[i].cacheKey, true, false, true),
313          singleBlocks[i]);
314      assertEquals(cache.getBlock(multiBlocks[i].cacheKey, true, false, true),
315          multiBlocks[i]);
316    }
317  }
318
319  @Test
320  public void testCacheEvictionThreePriorities() throws Exception {
321
322    long maxSize = 100000;
323    long blockSize = calculateBlockSize(maxSize, 10);
324
325    LruBlockCache cache = new LruBlockCache(maxSize, blockSize, false,
326        (int)Math.ceil(1.2*maxSize/blockSize),
327        LruBlockCache.DEFAULT_LOAD_FACTOR,
328        LruBlockCache.DEFAULT_CONCURRENCY_LEVEL,
329        0.98f, // min
330        0.99f, // acceptable
331        0.33f, // single
332        0.33f, // multi
333        0.34f, // memory
334        1.2f,  // limit
335        false,
336        16 * 1024 * 1024);
337
338    CachedItem [] singleBlocks = generateFixedBlocks(5, blockSize, "single");
339    CachedItem [] multiBlocks = generateFixedBlocks(5, blockSize, "multi");
340    CachedItem [] memoryBlocks = generateFixedBlocks(5, blockSize, "memory");
341
342    long expectedCacheSize = cache.heapSize();
343
344    // Add 3 blocks from each priority
345    for(int i=0;i<3;i++) {
346
347      // Just add single blocks
348      cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
349      expectedCacheSize += singleBlocks[i].cacheBlockHeapSize();
350
351      // Add and get multi blocks
352      cache.cacheBlock(multiBlocks[i].cacheKey, multiBlocks[i]);
353      expectedCacheSize += multiBlocks[i].cacheBlockHeapSize();
354      cache.getBlock(multiBlocks[i].cacheKey, true, false, true);
355
356      // Add memory blocks as such
357      cache.cacheBlock(memoryBlocks[i].cacheKey, memoryBlocks[i], true);
358      expectedCacheSize += memoryBlocks[i].cacheBlockHeapSize();
359
360    }
361
362    // Do not expect any evictions yet
363    assertEquals(0, cache.getStats().getEvictionCount());
364
365    // Verify cache size
366    assertEquals(expectedCacheSize, cache.heapSize());
367
368    // Insert a single block, oldest single should be evicted
369    cache.cacheBlock(singleBlocks[3].cacheKey, singleBlocks[3]);
370
371    // Single eviction, one thing evicted
372    assertEquals(1, cache.getStats().getEvictionCount());
373    assertEquals(1, cache.getStats().getEvictedCount());
374
375    // Verify oldest single block is the one evicted
376    assertEquals(null, cache.getBlock(singleBlocks[0].cacheKey, true, false, true));
377
378    // Change the oldest remaining single block to a multi
379    cache.getBlock(singleBlocks[1].cacheKey, true, false, true);
380
381    // Insert another single block
382    cache.cacheBlock(singleBlocks[4].cacheKey, singleBlocks[4]);
383
384    // Two evictions, two evicted.
385    assertEquals(2, cache.getStats().getEvictionCount());
386    assertEquals(2, cache.getStats().getEvictedCount());
387
388    // Oldest multi block should be evicted now
389    assertEquals(null, cache.getBlock(multiBlocks[0].cacheKey, true, false, true));
390
391    // Insert another memory block
392    cache.cacheBlock(memoryBlocks[3].cacheKey, memoryBlocks[3], true);
393
394    // Three evictions, three evicted.
395    assertEquals(3, cache.getStats().getEvictionCount());
396    assertEquals(3, cache.getStats().getEvictedCount());
397
398    // Oldest memory block should be evicted now
399    assertEquals(null, cache.getBlock(memoryBlocks[0].cacheKey, true, false, true));
400
401    // Add a block that is twice as big (should force two evictions)
402    CachedItem [] bigBlocks = generateFixedBlocks(3, blockSize*3, "big");
403    cache.cacheBlock(bigBlocks[0].cacheKey, bigBlocks[0]);
404
405    // Four evictions, six evicted (inserted block 3X size, expect +3 evicted)
406    assertEquals(4, cache.getStats().getEvictionCount());
407    assertEquals(6, cache.getStats().getEvictedCount());
408
409    // Expect three remaining singles to be evicted
410    assertEquals(null, cache.getBlock(singleBlocks[2].cacheKey, true, false, true));
411    assertEquals(null, cache.getBlock(singleBlocks[3].cacheKey, true, false, true));
412    assertEquals(null, cache.getBlock(singleBlocks[4].cacheKey, true, false, true));
413
414    // Make the big block a multi block
415    cache.getBlock(bigBlocks[0].cacheKey, true, false, true);
416
417    // Cache another single big block
418    cache.cacheBlock(bigBlocks[1].cacheKey, bigBlocks[1]);
419
420    // Five evictions, nine evicted (3 new)
421    assertEquals(5, cache.getStats().getEvictionCount());
422    assertEquals(9, cache.getStats().getEvictedCount());
423
424    // Expect three remaining multis to be evicted
425    assertEquals(null, cache.getBlock(singleBlocks[1].cacheKey, true, false, true));
426    assertEquals(null, cache.getBlock(multiBlocks[1].cacheKey, true, false, true));
427    assertEquals(null, cache.getBlock(multiBlocks[2].cacheKey, true, false, true));
428
429    // Cache a big memory block
430    cache.cacheBlock(bigBlocks[2].cacheKey, bigBlocks[2], true);
431
432    // Six evictions, twelve evicted (3 new)
433    assertEquals(6, cache.getStats().getEvictionCount());
434    assertEquals(12, cache.getStats().getEvictedCount());
435
436    // Expect three remaining in-memory to be evicted
437    assertEquals(null, cache.getBlock(memoryBlocks[1].cacheKey, true, false, true));
438    assertEquals(null, cache.getBlock(memoryBlocks[2].cacheKey, true, false, true));
439    assertEquals(null, cache.getBlock(memoryBlocks[3].cacheKey, true, false, true));
440  }
441
442  @Test
443  public void testCacheEvictionInMemoryForceMode() throws Exception {
444    long maxSize = 100000;
445    long blockSize = calculateBlockSize(maxSize, 10);
446
447    LruBlockCache cache = new LruBlockCache(maxSize, blockSize, false,
448        (int)Math.ceil(1.2*maxSize/blockSize),
449        LruBlockCache.DEFAULT_LOAD_FACTOR,
450        LruBlockCache.DEFAULT_CONCURRENCY_LEVEL,
451        0.98f, // min
452        0.99f, // acceptable
453        0.2f, // single
454        0.3f, // multi
455        0.5f, // memory
456        1.2f, // limit
457        true,
458        16 * 1024 * 1024);
459
460    CachedItem [] singleBlocks = generateFixedBlocks(10, blockSize, "single");
461    CachedItem [] multiBlocks = generateFixedBlocks(10, blockSize, "multi");
462    CachedItem [] memoryBlocks = generateFixedBlocks(10, blockSize, "memory");
463
464    long expectedCacheSize = cache.heapSize();
465
466    // 0. Add 5 single blocks and 4 multi blocks to make cache full, si:mu:me = 5:4:0
467    for(int i = 0; i < 4; i++) {
468      // Just add single blocks
469      cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
470      expectedCacheSize += singleBlocks[i].cacheBlockHeapSize();
471      // Add and get multi blocks
472      cache.cacheBlock(multiBlocks[i].cacheKey, multiBlocks[i]);
473      expectedCacheSize += multiBlocks[i].cacheBlockHeapSize();
474      cache.getBlock(multiBlocks[i].cacheKey, true, false, true);
475    }
476    // 5th single block
477    cache.cacheBlock(singleBlocks[4].cacheKey, singleBlocks[4]);
478    expectedCacheSize += singleBlocks[4].cacheBlockHeapSize();
479    // Do not expect any evictions yet
480    assertEquals(0, cache.getStats().getEvictionCount());
481    // Verify cache size
482    assertEquals(expectedCacheSize, cache.heapSize());
483
484    // 1. Insert a memory block, oldest single should be evicted, si:mu:me = 4:4:1
485    cache.cacheBlock(memoryBlocks[0].cacheKey, memoryBlocks[0], true);
486    // Single eviction, one block evicted
487    assertEquals(1, cache.getStats().getEvictionCount());
488    assertEquals(1, cache.getStats().getEvictedCount());
489    // Verify oldest single block (index = 0) is the one evicted
490    assertEquals(null, cache.getBlock(singleBlocks[0].cacheKey, true, false, true));
491
492    // 2. Insert another memory block, another single evicted, si:mu:me = 3:4:2
493    cache.cacheBlock(memoryBlocks[1].cacheKey, memoryBlocks[1], true);
494    // Two evictions, two evicted.
495    assertEquals(2, cache.getStats().getEvictionCount());
496    assertEquals(2, cache.getStats().getEvictedCount());
497    // Current oldest single block (index = 1) should be evicted now
498    assertEquals(null, cache.getBlock(singleBlocks[1].cacheKey, true, false, true));
499
500    // 3. Insert 4 memory blocks, 2 single and 2 multi evicted, si:mu:me = 1:2:6
501    cache.cacheBlock(memoryBlocks[2].cacheKey, memoryBlocks[2], true);
502    cache.cacheBlock(memoryBlocks[3].cacheKey, memoryBlocks[3], true);
503    cache.cacheBlock(memoryBlocks[4].cacheKey, memoryBlocks[4], true);
504    cache.cacheBlock(memoryBlocks[5].cacheKey, memoryBlocks[5], true);
505    // Three evictions, three evicted.
506    assertEquals(6, cache.getStats().getEvictionCount());
507    assertEquals(6, cache.getStats().getEvictedCount());
508    // two oldest single blocks and two oldest multi blocks evicted
509    assertEquals(null, cache.getBlock(singleBlocks[2].cacheKey, true, false, true));
510    assertEquals(null, cache.getBlock(singleBlocks[3].cacheKey, true, false, true));
511    assertEquals(null, cache.getBlock(multiBlocks[0].cacheKey, true, false, true));
512    assertEquals(null, cache.getBlock(multiBlocks[1].cacheKey, true, false, true));
513
514    // 4. Insert 3 memory blocks, the remaining 1 single and 2 multi evicted
515    // si:mu:me = 0:0:9
516    cache.cacheBlock(memoryBlocks[6].cacheKey, memoryBlocks[6], true);
517    cache.cacheBlock(memoryBlocks[7].cacheKey, memoryBlocks[7], true);
518    cache.cacheBlock(memoryBlocks[8].cacheKey, memoryBlocks[8], true);
519    // Three evictions, three evicted.
520    assertEquals(9, cache.getStats().getEvictionCount());
521    assertEquals(9, cache.getStats().getEvictedCount());
522    // one oldest single block and two oldest multi blocks evicted
523    assertEquals(null, cache.getBlock(singleBlocks[4].cacheKey, true, false, true));
524    assertEquals(null, cache.getBlock(multiBlocks[2].cacheKey, true, false, true));
525    assertEquals(null, cache.getBlock(multiBlocks[3].cacheKey, true, false, true));
526
527    // 5. Insert one memory block, the oldest memory evicted
528    // si:mu:me = 0:0:9
529    cache.cacheBlock(memoryBlocks[9].cacheKey, memoryBlocks[9], true);
530    // one eviction, one evicted.
531    assertEquals(10, cache.getStats().getEvictionCount());
532    assertEquals(10, cache.getStats().getEvictedCount());
533    // oldest memory block evicted
534    assertEquals(null, cache.getBlock(memoryBlocks[0].cacheKey, true, false, true));
535
536    // 6. Insert one new single block, itself evicted immediately since
537    //    all blocks in cache are memory-type which have higher priority
538    // si:mu:me = 0:0:9 (no change)
539    cache.cacheBlock(singleBlocks[9].cacheKey, singleBlocks[9]);
540    // one eviction, one evicted.
541    assertEquals(11, cache.getStats().getEvictionCount());
542    assertEquals(11, cache.getStats().getEvictedCount());
543    // the single block just cached now evicted (can't evict memory)
544    assertEquals(null, cache.getBlock(singleBlocks[9].cacheKey, true, false, true));
545  }
546
547  // test scan resistance
548  @Test
549  public void testScanResistance() throws Exception {
550
551    long maxSize = 100000;
552    long blockSize = calculateBlockSize(maxSize, 10);
553
554    LruBlockCache cache = new LruBlockCache(maxSize, blockSize, false,
555        (int)Math.ceil(1.2*maxSize/blockSize),
556        LruBlockCache.DEFAULT_LOAD_FACTOR,
557        LruBlockCache.DEFAULT_CONCURRENCY_LEVEL,
558        0.66f, // min
559        0.99f, // acceptable
560        0.33f, // single
561        0.33f, // multi
562        0.34f, // memory
563        1.2f,  // limit
564        false,
565        16 * 1024 * 1024);
566
567    CachedItem [] singleBlocks = generateFixedBlocks(20, blockSize, "single");
568    CachedItem [] multiBlocks = generateFixedBlocks(5, blockSize, "multi");
569
570    // Add 5 multi blocks
571    for (CachedItem block : multiBlocks) {
572      cache.cacheBlock(block.cacheKey, block);
573      cache.getBlock(block.cacheKey, true, false, true);
574    }
575
576    // Add 5 single blocks
577    for(int i=0;i<5;i++) {
578      cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
579    }
580
581    // An eviction ran
582    assertEquals(1, cache.getStats().getEvictionCount());
583
584    // To drop down to 2/3 capacity, we'll need to evict 4 blocks
585    assertEquals(4, cache.getStats().getEvictedCount());
586
587    // Should have been taken off equally from single and multi
588    assertEquals(null, cache.getBlock(singleBlocks[0].cacheKey, true, false, true));
589    assertEquals(null, cache.getBlock(singleBlocks[1].cacheKey, true, false, true));
590    assertEquals(null, cache.getBlock(multiBlocks[0].cacheKey, true, false, true));
591    assertEquals(null, cache.getBlock(multiBlocks[1].cacheKey, true, false, true));
592
593    // Let's keep "scanning" by adding single blocks.  From here on we only
594    // expect evictions from the single bucket.
595
596    // Every time we reach 10 total blocks (every 4 inserts) we get 4 single
597    // blocks evicted.  Inserting 13 blocks should yield 3 more evictions and
598    // 12 more evicted.
599
600    for(int i=5;i<18;i++) {
601      cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
602    }
603
604    // 4 total evictions, 16 total evicted
605    assertEquals(4, cache.getStats().getEvictionCount());
606    assertEquals(16, cache.getStats().getEvictedCount());
607
608    // Should now have 7 total blocks
609    assertEquals(7, cache.getBlockCount());
610
611  }
612
613  @Test
614  public void testMaxBlockSize() throws Exception {
615    long maxSize = 100000;
616    long blockSize = calculateBlockSize(maxSize, 10);
617
618    LruBlockCache cache = new LruBlockCache(maxSize, blockSize, false,
619        (int)Math.ceil(1.2*maxSize/blockSize),
620        LruBlockCache.DEFAULT_LOAD_FACTOR,
621        LruBlockCache.DEFAULT_CONCURRENCY_LEVEL,
622        0.66f, // min
623        0.99f, // acceptable
624        0.33f, // single
625        0.33f, // multi
626        0.34f, // memory
627        1.2f,  // limit
628        false,
629        1024);
630    CachedItem [] tooLong = generateFixedBlocks(10, 1024+5, "long");
631    CachedItem [] small = generateFixedBlocks(15, 600, "small");
632
633
634    for (CachedItem i:tooLong) {
635      cache.cacheBlock(i.cacheKey, i);
636    }
637    for (CachedItem i:small) {
638      cache.cacheBlock(i.cacheKey, i);
639    }
640    assertEquals(15,cache.getBlockCount());
641    for (CachedItem i:small) {
642      assertNotNull(cache.getBlock(i.cacheKey, true, false, false));
643    }
644    for (CachedItem i:tooLong) {
645      assertNull(cache.getBlock(i.cacheKey, true, false, false));
646    }
647
648    assertEquals(10, cache.getStats().getFailedInserts());
649  }
650
651  // test setMaxSize
652  @Test
653  public void testResizeBlockCache() throws Exception {
654
655    long maxSize = 300000;
656    long blockSize = calculateBlockSize(maxSize, 31);
657
658    LruBlockCache cache = new LruBlockCache(maxSize, blockSize, false,
659        (int)Math.ceil(1.2*maxSize/blockSize),
660        LruBlockCache.DEFAULT_LOAD_FACTOR,
661        LruBlockCache.DEFAULT_CONCURRENCY_LEVEL,
662        0.98f, // min
663        0.99f, // acceptable
664        0.33f, // single
665        0.33f, // multi
666        0.34f, // memory
667        1.2f,  // limit
668        false,
669        16 * 1024 * 1024);
670
671    CachedItem [] singleBlocks = generateFixedBlocks(10, blockSize, "single");
672    CachedItem [] multiBlocks = generateFixedBlocks(10, blockSize, "multi");
673    CachedItem [] memoryBlocks = generateFixedBlocks(10, blockSize, "memory");
674
675    // Add all blocks from all priorities
676    for(int i=0;i<10;i++) {
677
678      // Just add single blocks
679      cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
680
681      // Add and get multi blocks
682      cache.cacheBlock(multiBlocks[i].cacheKey, multiBlocks[i]);
683      cache.getBlock(multiBlocks[i].cacheKey, true, false, true);
684
685      // Add memory blocks as such
686      cache.cacheBlock(memoryBlocks[i].cacheKey, memoryBlocks[i], true);
687    }
688
689    // Do not expect any evictions yet
690    assertEquals(0, cache.getStats().getEvictionCount());
691
692    // Resize to half capacity plus an extra block (otherwise we evict an extra)
693    cache.setMaxSize((long)(maxSize * 0.5f));
694
695    // Should have run a single eviction
696    assertEquals(1, cache.getStats().getEvictionCount());
697
698    // And we expect 1/2 of the blocks to be evicted
699    assertEquals(15, cache.getStats().getEvictedCount());
700
701    // And the oldest 5 blocks from each category should be gone
702    for(int i=0;i<5;i++) {
703      assertEquals(null, cache.getBlock(singleBlocks[i].cacheKey, true, false, true));
704      assertEquals(null, cache.getBlock(multiBlocks[i].cacheKey, true, false, true));
705      assertEquals(null, cache.getBlock(memoryBlocks[i].cacheKey, true, false, true));
706    }
707
708    // And the newest 5 blocks should still be accessible
709    for(int i=5;i<10;i++) {
710      assertEquals(singleBlocks[i], cache.getBlock(singleBlocks[i].cacheKey, true, false, true));
711      assertEquals(multiBlocks[i], cache.getBlock(multiBlocks[i].cacheKey, true, false, true));
712      assertEquals(memoryBlocks[i], cache.getBlock(memoryBlocks[i].cacheKey, true, false, true));
713    }
714  }
715
716  // test metricsPastNPeriods
717  @Test
718  public void testPastNPeriodsMetrics() throws Exception {
719   double delta = 0.01;
720
721    // 3 total periods
722    CacheStats stats = new CacheStats("test", 3);
723
724    // No accesses, should be 0
725    stats.rollMetricsPeriod();
726    assertEquals(0.0, stats.getHitRatioPastNPeriods(), delta);
727    assertEquals(0.0, stats.getHitCachingRatioPastNPeriods(), delta);
728
729    // period 1, 1 hit caching, 1 hit non-caching, 2 miss non-caching
730    // should be (2/4)=0.5 and (1/1)=1
731    stats.hit(false, true, BlockType.DATA);
732    stats.hit(true, true, BlockType.DATA);
733    stats.miss(false, false, BlockType.DATA);
734    stats.miss(false, false, BlockType.DATA);
735    stats.rollMetricsPeriod();
736    assertEquals(0.5, stats.getHitRatioPastNPeriods(), delta);
737    assertEquals(1.0, stats.getHitCachingRatioPastNPeriods(), delta);
738
739    // period 2, 1 miss caching, 3 miss non-caching
740    // should be (2/8)=0.25 and (1/2)=0.5
741    stats.miss(true, false, BlockType.DATA);
742    stats.miss(false, false, BlockType.DATA);
743    stats.miss(false, false, BlockType.DATA);
744    stats.miss(false, false, BlockType.DATA);
745    stats.rollMetricsPeriod();
746    assertEquals(0.25, stats.getHitRatioPastNPeriods(), delta);
747    assertEquals(0.5, stats.getHitCachingRatioPastNPeriods(), delta);
748
749    // period 3, 2 hits of each type
750    // should be (6/12)=0.5 and (3/4)=0.75
751    stats.hit(false, true, BlockType.DATA);
752    stats.hit(true, true, BlockType.DATA);
753    stats.hit(false, true, BlockType.DATA);
754    stats.hit(true, true, BlockType.DATA);
755    stats.rollMetricsPeriod();
756    assertEquals(0.5, stats.getHitRatioPastNPeriods(), delta);
757    assertEquals(0.75, stats.getHitCachingRatioPastNPeriods(), delta);
758
759    // period 4, evict period 1, two caching misses
760    // should be (4/10)=0.4 and (2/5)=0.4
761    stats.miss(true, false, BlockType.DATA);
762    stats.miss(true, false, BlockType.DATA);
763    stats.rollMetricsPeriod();
764    assertEquals(0.4, stats.getHitRatioPastNPeriods(), delta);
765    assertEquals(0.4, stats.getHitCachingRatioPastNPeriods(), delta);
766
767    // period 5, evict period 2, 2 caching misses, 2 non-caching hit
768    // should be (6/10)=0.6 and (2/6)=1/3
769    stats.miss(true, false, BlockType.DATA);
770    stats.miss(true, false, BlockType.DATA);
771    stats.hit(false, true, BlockType.DATA);
772    stats.hit(false, true, BlockType.DATA);
773    stats.rollMetricsPeriod();
774    assertEquals(0.6, stats.getHitRatioPastNPeriods(), delta);
775    assertEquals((double)1/3, stats.getHitCachingRatioPastNPeriods(), delta);
776
777    // period 6, evict period 3
778    // should be (2/6)=1/3 and (0/4)=0
779    stats.rollMetricsPeriod();
780    assertEquals((double)1/3, stats.getHitRatioPastNPeriods(), delta);
781    assertEquals(0.0, stats.getHitCachingRatioPastNPeriods(), delta);
782
783    // period 7, evict period 4
784    // should be (2/4)=0.5 and (0/2)=0
785    stats.rollMetricsPeriod();
786    assertEquals(0.5, stats.getHitRatioPastNPeriods(), delta);
787    assertEquals(0.0, stats.getHitCachingRatioPastNPeriods(), delta);
788
789    // period 8, evict period 5
790    // should be 0 and 0
791    stats.rollMetricsPeriod();
792    assertEquals(0.0, stats.getHitRatioPastNPeriods(), delta);
793    assertEquals(0.0, stats.getHitCachingRatioPastNPeriods(), delta);
794
795    // period 9, one of each
796    // should be (2/4)=0.5 and (1/2)=0.5
797    stats.miss(true, false, BlockType.DATA);
798    stats.miss(false, false, BlockType.DATA);
799    stats.hit(true, true, BlockType.DATA);
800    stats.hit(false, true, BlockType.DATA);
801    stats.rollMetricsPeriod();
802    assertEquals(0.5, stats.getHitRatioPastNPeriods(), delta);
803    assertEquals(0.5, stats.getHitCachingRatioPastNPeriods(), delta);
804  }
805
806  private CachedItem [] generateFixedBlocks(int numBlocks, int size, String pfx) {
807    CachedItem [] blocks = new CachedItem[numBlocks];
808    for(int i=0;i<numBlocks;i++) {
809      blocks[i] = new CachedItem(pfx + i, size);
810    }
811    return blocks;
812  }
813
814  private CachedItem [] generateFixedBlocks(int numBlocks, long size, String pfx) {
815    return generateFixedBlocks(numBlocks, (int)size, pfx);
816  }
817
818  private CachedItem [] generateRandomBlocks(int numBlocks, long maxSize) {
819    CachedItem [] blocks = new CachedItem[numBlocks];
820    Random r = new Random();
821    for(int i=0;i<numBlocks;i++) {
822      blocks[i] = new CachedItem("block" + i, r.nextInt((int)maxSize)+1);
823    }
824    return blocks;
825  }
826
827  private long calculateBlockSize(long maxSize, int numBlocks) {
828    long roughBlockSize = maxSize / numBlocks;
829    int numEntries = (int)Math.ceil((1.2)*maxSize/roughBlockSize);
830    long totalOverhead = LruBlockCache.CACHE_FIXED_OVERHEAD +
831        ClassSize.CONCURRENT_HASHMAP +
832        (numEntries * ClassSize.CONCURRENT_HASHMAP_ENTRY) +
833        (LruBlockCache.DEFAULT_CONCURRENCY_LEVEL * ClassSize.CONCURRENT_HASHMAP_SEGMENT);
834    long negateBlockSize = (long)(totalOverhead/numEntries);
835    negateBlockSize += LruCachedBlock.PER_BLOCK_OVERHEAD;
836    return ClassSize.align((long)Math.floor((roughBlockSize - negateBlockSize)*0.99f));
837  }
838
839  private long calculateBlockSizeDefault(long maxSize, int numBlocks) {
840    long roughBlockSize = maxSize / numBlocks;
841    int numEntries = (int)Math.ceil((1.2)*maxSize/roughBlockSize);
842    long totalOverhead = LruBlockCache.CACHE_FIXED_OVERHEAD +
843        ClassSize.CONCURRENT_HASHMAP +
844        (numEntries * ClassSize.CONCURRENT_HASHMAP_ENTRY) +
845        (LruBlockCache.DEFAULT_CONCURRENCY_LEVEL * ClassSize.CONCURRENT_HASHMAP_SEGMENT);
846    long negateBlockSize = totalOverhead / numEntries;
847    negateBlockSize += LruCachedBlock.PER_BLOCK_OVERHEAD;
848    return ClassSize.align((long)Math.floor((roughBlockSize - negateBlockSize)*
849        LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
850  }
851
852  private static class CachedItem implements Cacheable {
853    BlockCacheKey cacheKey;
854    int size;
855
856    CachedItem(String blockName, int size, int offset) {
857      this.cacheKey = new BlockCacheKey(blockName, offset);
858      this.size = size;
859    }
860
861    CachedItem(String blockName, int size) {
862      this.cacheKey = new BlockCacheKey(blockName, 0);
863      this.size = size;
864    }
865
866    /** The size of this item reported to the block cache layer */
867    @Override
868    public long heapSize() {
869      return ClassSize.align(size);
870    }
871
872    /** Size of the cache block holding this item. Used for verification. */
873    public long cacheBlockHeapSize() {
874      return LruCachedBlock.PER_BLOCK_OVERHEAD
875          + ClassSize.align(cacheKey.heapSize())
876          + ClassSize.align(size);
877    }
878
879    @Override
880    public int getSerializedLength() {
881      return 0;
882    }
883
884    @Override
885    public CacheableDeserializer<Cacheable> getDeserializer() {
886      return null;
887    }
888
889    @Override
890    public void serialize(ByteBuffer destination) {
891    }
892
893    @Override
894    public BlockType getBlockType() {
895      return BlockType.DATA;
896    }
897
898    @Override
899    public MemoryType getMemoryType() {
900      return MemoryType.EXCLUSIVE;
901    }
902
903  }
904
905}
906