View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.io.hfile;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertNotNull;
23  import static org.junit.Assert.assertNull;
24  import static org.junit.Assert.assertTrue;
25  
26  import java.nio.ByteBuffer;
27  import java.util.Random;
28  
29  import org.apache.hadoop.hbase.testclassification.SmallTests;
30  import org.apache.hadoop.hbase.io.HeapSize;
31  import org.apache.hadoop.hbase.io.hfile.LruBlockCache.EvictionThread;
32  import org.apache.hadoop.hbase.util.ClassSize;
33  import org.junit.Test;
34  import org.junit.experimental.categories.Category;
35  
36  /**
37   * Tests the concurrent LruBlockCache.<p>
38   *
39   * Tests will ensure it grows and shrinks in size properly,
40   * evictions run when they're supposed to and do what they should,
41   * and that cached blocks are accessible when expected to be.
42   */
43  @Category(SmallTests.class)
44  public class TestLruBlockCache {
45  
46  
47    @Test
48    public void testBackgroundEvictionThread() throws Exception {
49      long maxSize = 100000;
50      int numBlocks = 9;
51      long blockSize = calculateBlockSizeDefault(maxSize, numBlocks);
52      assertTrue("calculateBlockSize appears broken.", blockSize * numBlocks <= maxSize);
53  
54      LruBlockCache cache = new LruBlockCache(maxSize,blockSize);
55      EvictionThread evictionThread = cache.getEvictionThread();
56      assertTrue(evictionThread != null);
57  
58      CachedItem[] blocks = generateFixedBlocks(numBlocks + 1, blockSize, "block");
59  
60      // Make sure eviction thread has entered run method
61      while (!evictionThread.isEnteringRun()) {
62        Thread.sleep(1);
63      }
64  
65      // Add all the blocks
66      for (CachedItem block : blocks) {
67        cache.cacheBlock(block.cacheKey, block);
68      }
69  
70      // wait until at least one eviction has run
71      int n = 0;
72      while(cache.getStats().getEvictionCount() == 0) {
73        Thread.sleep(200);
74        assertTrue("Eviction never happened.", n++ < 20);
75      }
76  
77      // let cache stabilize
78      // On some systems, the cache will run multiple evictions before it attains
79      // steady-state. For instance, after populating the cache with 10 blocks,
80      // the first eviction evicts a single block and then a second eviction
81      // evicts another. I think this is due to the delta between minSize and
82      // acceptableSize, combined with variance between object overhead on
83      // different environments.
84      n = 0;
85      for (long prevCnt = 0 /* < number of blocks added */,
86                curCnt = cache.getBlockCount();
87          prevCnt != curCnt; prevCnt = curCnt, curCnt = cache.getBlockCount()) {
88        Thread.sleep(200);
89        assertTrue("Cache never stabilized.", n++ < 20);
90      }
91  
92      long evictionCount = cache.getStats().getEvictionCount();
93      assertTrue(evictionCount >= 1);
94      System.out.println("Background Evictions run: " + evictionCount);
95    }
96  
97    @Test
98    public void testCacheSimple() throws Exception {
99  
100     long maxSize = 1000000;
101     long blockSize = calculateBlockSizeDefault(maxSize, 101);
102 
103     LruBlockCache cache = new LruBlockCache(maxSize, blockSize);
104 
105     CachedItem [] blocks = generateRandomBlocks(100, blockSize);
106 
107     long expectedCacheSize = cache.heapSize();
108 
109     // Confirm empty
110     for (CachedItem block : blocks) {
111       assertTrue(cache.getBlock(block.cacheKey, true, false, true) == null);
112     }
113 
114     // Add blocks
115     for (CachedItem block : blocks) {
116       cache.cacheBlock(block.cacheKey, block);
117       expectedCacheSize += block.cacheBlockHeapSize();
118     }
119 
120     // Verify correctly calculated cache heap size
121     assertEquals(expectedCacheSize, cache.heapSize());
122 
123     // Check if all blocks are properly cached and retrieved
124     for (CachedItem block : blocks) {
125       HeapSize buf = cache.getBlock(block.cacheKey, true, false, true);
126       assertTrue(buf != null);
127       assertEquals(buf.heapSize(), block.heapSize());
128     }
129 
130     // Re-add same blocks and ensure nothing has changed
131     long expectedBlockCount = cache.getBlockCount();
132     for (CachedItem block : blocks) {
133       cache.cacheBlock(block.cacheKey, block);
134     }
135     assertEquals(
136             "Cache should ignore cache requests for blocks already in cache",
137             expectedBlockCount, cache.getBlockCount());
138     
139     // Verify correctly calculated cache heap size
140     assertEquals(expectedCacheSize, cache.heapSize());
141 
142     // Check if all blocks are properly cached and retrieved
143     for (CachedItem block : blocks) {
144       HeapSize buf = cache.getBlock(block.cacheKey, true, false, true);
145       assertTrue(buf != null);
146       assertEquals(buf.heapSize(), block.heapSize());
147     }
148 
149     // Expect no evictions
150     assertEquals(0, cache.getStats().getEvictionCount());
151     Thread t = new LruBlockCache.StatisticsThread(cache);
152     t.start();
153     t.join();
154   }
155 
156   @Test
157   public void testCacheEvictionSimple() throws Exception {
158 
159     long maxSize = 100000;
160     long blockSize = calculateBlockSizeDefault(maxSize, 10);
161 
162     LruBlockCache cache = new LruBlockCache(maxSize,blockSize,false);
163 
164     CachedItem [] blocks = generateFixedBlocks(10, blockSize, "block");
165 
166     long expectedCacheSize = cache.heapSize();
167 
168     // Add all the blocks
169     for (CachedItem block : blocks) {
170       cache.cacheBlock(block.cacheKey, block);
171       expectedCacheSize += block.cacheBlockHeapSize();
172     }
173 
174     // A single eviction run should have occurred
175     assertEquals(1, cache.getStats().getEvictionCount());
176 
177     // Our expected size overruns acceptable limit
178     assertTrue(expectedCacheSize >
179       (maxSize * LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
180 
181     // But the cache did not grow beyond max
182     assertTrue(cache.heapSize() < maxSize);
183 
184     // And is still below the acceptable limit
185     assertTrue(cache.heapSize() <
186         (maxSize * LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
187 
188     // All blocks except block 0  should be in the cache
189     assertTrue(cache.getBlock(blocks[0].cacheKey, true, false, true) == null);
190     for(int i=1;i<blocks.length;i++) {
191       assertEquals(cache.getBlock(blocks[i].cacheKey, true, false, true),
192           blocks[i]);
193     }
194   }
195 
196   @Test
197   public void testCacheEvictionTwoPriorities() throws Exception {
198 
199     long maxSize = 100000;
200     long blockSize = calculateBlockSizeDefault(maxSize, 10);
201 
202     LruBlockCache cache = new LruBlockCache(maxSize,blockSize,false);
203 
204     CachedItem [] singleBlocks = generateFixedBlocks(5, 10000, "single");
205     CachedItem [] multiBlocks = generateFixedBlocks(5, 10000, "multi");
206 
207     long expectedCacheSize = cache.heapSize();
208 
209     // Add and get the multi blocks
210     for (CachedItem block : multiBlocks) {
211       cache.cacheBlock(block.cacheKey, block);
212       expectedCacheSize += block.cacheBlockHeapSize();
213       assertEquals(cache.getBlock(block.cacheKey, true, false, true), block);
214     }
215 
216     // Add the single blocks (no get)
217     for (CachedItem block : singleBlocks) {
218       cache.cacheBlock(block.cacheKey, block);
219       expectedCacheSize += block.heapSize();
220     }
221 
222     // A single eviction run should have occurred
223     assertEquals(cache.getStats().getEvictionCount(), 1);
224 
225     // We expect two entries evicted
226     assertEquals(cache.getStats().getEvictedCount(), 2);
227 
228     // Our expected size overruns acceptable limit
229     assertTrue(expectedCacheSize >
230       (maxSize * LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
231 
232     // But the cache did not grow beyond max
233     assertTrue(cache.heapSize() <= maxSize);
234 
235     // And is now below the acceptable limit
236     assertTrue(cache.heapSize() <=
237         (maxSize * LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
238 
239     // We expect fairness across the two priorities.
240     // This test makes multi go barely over its limit, in-memory
241     // empty, and the rest in single.  Two single evictions and
242     // one multi eviction expected.
243     assertTrue(cache.getBlock(singleBlocks[0].cacheKey, true, false, true) == null);
244     assertTrue(cache.getBlock(multiBlocks[0].cacheKey, true, false, true) == null);
245 
246     // And all others to be cached
247     for(int i=1;i<4;i++) {
248       assertEquals(cache.getBlock(singleBlocks[i].cacheKey, true, false, true),
249           singleBlocks[i]);
250       assertEquals(cache.getBlock(multiBlocks[i].cacheKey, true, false, true),
251           multiBlocks[i]);
252     }
253   }
254 
255   @Test
256   public void testCacheEvictionThreePriorities() throws Exception {
257 
258     long maxSize = 100000;
259     long blockSize = calculateBlockSize(maxSize, 10);
260 
261     LruBlockCache cache = new LruBlockCache(maxSize, blockSize, false,
262         (int)Math.ceil(1.2*maxSize/blockSize),
263         LruBlockCache.DEFAULT_LOAD_FACTOR,
264         LruBlockCache.DEFAULT_CONCURRENCY_LEVEL,
265         0.98f, // min
266         0.99f, // acceptable
267         0.33f, // single
268         0.33f, // multi
269         0.34f, // memory
270         1.2f,  // limit
271         false,
272         16 * 1024 * 1024);
273 
274     CachedItem [] singleBlocks = generateFixedBlocks(5, blockSize, "single");
275     CachedItem [] multiBlocks = generateFixedBlocks(5, blockSize, "multi");
276     CachedItem [] memoryBlocks = generateFixedBlocks(5, blockSize, "memory");
277 
278     long expectedCacheSize = cache.heapSize();
279 
280     // Add 3 blocks from each priority
281     for(int i=0;i<3;i++) {
282 
283       // Just add single blocks
284       cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
285       expectedCacheSize += singleBlocks[i].cacheBlockHeapSize();
286 
287       // Add and get multi blocks
288       cache.cacheBlock(multiBlocks[i].cacheKey, multiBlocks[i]);
289       expectedCacheSize += multiBlocks[i].cacheBlockHeapSize();
290       cache.getBlock(multiBlocks[i].cacheKey, true, false, true);
291 
292       // Add memory blocks as such
293       cache.cacheBlock(memoryBlocks[i].cacheKey, memoryBlocks[i], true, false);
294       expectedCacheSize += memoryBlocks[i].cacheBlockHeapSize();
295 
296     }
297 
298     // Do not expect any evictions yet
299     assertEquals(0, cache.getStats().getEvictionCount());
300 
301     // Verify cache size
302     assertEquals(expectedCacheSize, cache.heapSize());
303 
304     // Insert a single block, oldest single should be evicted
305     cache.cacheBlock(singleBlocks[3].cacheKey, singleBlocks[3]);
306 
307     // Single eviction, one thing evicted
308     assertEquals(1, cache.getStats().getEvictionCount());
309     assertEquals(1, cache.getStats().getEvictedCount());
310 
311     // Verify oldest single block is the one evicted
312     assertEquals(null, cache.getBlock(singleBlocks[0].cacheKey, true, false, true));
313 
314     // Change the oldest remaining single block to a multi
315     cache.getBlock(singleBlocks[1].cacheKey, true, false, true);
316 
317     // Insert another single block
318     cache.cacheBlock(singleBlocks[4].cacheKey, singleBlocks[4]);
319 
320     // Two evictions, two evicted.
321     assertEquals(2, cache.getStats().getEvictionCount());
322     assertEquals(2, cache.getStats().getEvictedCount());
323 
324     // Oldest multi block should be evicted now
325     assertEquals(null, cache.getBlock(multiBlocks[0].cacheKey, true, false, true));
326 
327     // Insert another memory block
328     cache.cacheBlock(memoryBlocks[3].cacheKey, memoryBlocks[3], true, false);
329 
330     // Three evictions, three evicted.
331     assertEquals(3, cache.getStats().getEvictionCount());
332     assertEquals(3, cache.getStats().getEvictedCount());
333 
334     // Oldest memory block should be evicted now
335     assertEquals(null, cache.getBlock(memoryBlocks[0].cacheKey, true, false, true));
336 
337     // Add a block that is twice as big (should force two evictions)
338     CachedItem [] bigBlocks = generateFixedBlocks(3, blockSize*3, "big");
339     cache.cacheBlock(bigBlocks[0].cacheKey, bigBlocks[0]);
340 
341     // Four evictions, six evicted (inserted block 3X size, expect +3 evicted)
342     assertEquals(4, cache.getStats().getEvictionCount());
343     assertEquals(6, cache.getStats().getEvictedCount());
344 
345     // Expect three remaining singles to be evicted
346     assertEquals(null, cache.getBlock(singleBlocks[2].cacheKey, true, false, true));
347     assertEquals(null, cache.getBlock(singleBlocks[3].cacheKey, true, false, true));
348     assertEquals(null, cache.getBlock(singleBlocks[4].cacheKey, true, false, true));
349 
350     // Make the big block a multi block
351     cache.getBlock(bigBlocks[0].cacheKey, true, false, true);
352 
353     // Cache another single big block
354     cache.cacheBlock(bigBlocks[1].cacheKey, bigBlocks[1]);
355 
356     // Five evictions, nine evicted (3 new)
357     assertEquals(5, cache.getStats().getEvictionCount());
358     assertEquals(9, cache.getStats().getEvictedCount());
359 
360     // Expect three remaining multis to be evicted
361     assertEquals(null, cache.getBlock(singleBlocks[1].cacheKey, true, false, true));
362     assertEquals(null, cache.getBlock(multiBlocks[1].cacheKey, true, false, true));
363     assertEquals(null, cache.getBlock(multiBlocks[2].cacheKey, true, false, true));
364 
365     // Cache a big memory block
366     cache.cacheBlock(bigBlocks[2].cacheKey, bigBlocks[2], true, false);
367 
368     // Six evictions, twelve evicted (3 new)
369     assertEquals(6, cache.getStats().getEvictionCount());
370     assertEquals(12, cache.getStats().getEvictedCount());
371 
372     // Expect three remaining in-memory to be evicted
373     assertEquals(null, cache.getBlock(memoryBlocks[1].cacheKey, true, false, true));
374     assertEquals(null, cache.getBlock(memoryBlocks[2].cacheKey, true, false, true));
375     assertEquals(null, cache.getBlock(memoryBlocks[3].cacheKey, true, false, true));
376   }
377 
378   @Test
379   public void testCacheEvictionInMemoryForceMode() throws Exception {
380     long maxSize = 100000;
381     long blockSize = calculateBlockSize(maxSize, 10);
382 
383     LruBlockCache cache = new LruBlockCache(maxSize, blockSize, false,
384         (int)Math.ceil(1.2*maxSize/blockSize),
385         LruBlockCache.DEFAULT_LOAD_FACTOR,
386         LruBlockCache.DEFAULT_CONCURRENCY_LEVEL,
387         0.98f, // min
388         0.99f, // acceptable
389         0.2f, // single
390         0.3f, // multi
391         0.5f, // memory
392         1.2f, // limit
393         true,
394         16 * 1024 * 1024);
395 
396     CachedItem [] singleBlocks = generateFixedBlocks(10, blockSize, "single");
397     CachedItem [] multiBlocks = generateFixedBlocks(10, blockSize, "multi");
398     CachedItem [] memoryBlocks = generateFixedBlocks(10, blockSize, "memory");
399 
400     long expectedCacheSize = cache.heapSize();
401 
402     // 0. Add 5 single blocks and 4 multi blocks to make cache full, si:mu:me = 5:4:0
403     for(int i = 0; i < 4; i++) {
404       // Just add single blocks
405       cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
406       expectedCacheSize += singleBlocks[i].cacheBlockHeapSize();
407       // Add and get multi blocks
408       cache.cacheBlock(multiBlocks[i].cacheKey, multiBlocks[i]);
409       expectedCacheSize += multiBlocks[i].cacheBlockHeapSize();
410       cache.getBlock(multiBlocks[i].cacheKey, true, false, true);
411     }
412     // 5th single block
413     cache.cacheBlock(singleBlocks[4].cacheKey, singleBlocks[4]);
414     expectedCacheSize += singleBlocks[4].cacheBlockHeapSize();
415     // Do not expect any evictions yet
416     assertEquals(0, cache.getStats().getEvictionCount());
417     // Verify cache size
418     assertEquals(expectedCacheSize, cache.heapSize());
419 
420     // 1. Insert a memory block, oldest single should be evicted, si:mu:me = 4:4:1
421     cache.cacheBlock(memoryBlocks[0].cacheKey, memoryBlocks[0], true, false);
422     // Single eviction, one block evicted
423     assertEquals(1, cache.getStats().getEvictionCount());
424     assertEquals(1, cache.getStats().getEvictedCount());
425     // Verify oldest single block (index = 0) is the one evicted
426     assertEquals(null, cache.getBlock(singleBlocks[0].cacheKey, true, false, true));
427 
428     // 2. Insert another memory block, another single evicted, si:mu:me = 3:4:2
429     cache.cacheBlock(memoryBlocks[1].cacheKey, memoryBlocks[1], true, false);
430     // Two evictions, two evicted.
431     assertEquals(2, cache.getStats().getEvictionCount());
432     assertEquals(2, cache.getStats().getEvictedCount());
433     // Current oldest single block (index = 1) should be evicted now
434     assertEquals(null, cache.getBlock(singleBlocks[1].cacheKey, true, false, true));
435 
436     // 3. Insert 4 memory blocks, 2 single and 2 multi evicted, si:mu:me = 1:2:6
437     cache.cacheBlock(memoryBlocks[2].cacheKey, memoryBlocks[2], true, false);
438     cache.cacheBlock(memoryBlocks[3].cacheKey, memoryBlocks[3], true, false);
439     cache.cacheBlock(memoryBlocks[4].cacheKey, memoryBlocks[4], true, false);
440     cache.cacheBlock(memoryBlocks[5].cacheKey, memoryBlocks[5], true, false);
441     // Three evictions, three evicted.
442     assertEquals(6, cache.getStats().getEvictionCount());
443     assertEquals(6, cache.getStats().getEvictedCount());
444     // two oldest single blocks and two oldest multi blocks evicted
445     assertEquals(null, cache.getBlock(singleBlocks[2].cacheKey, true, false, true));
446     assertEquals(null, cache.getBlock(singleBlocks[3].cacheKey, true, false, true));
447     assertEquals(null, cache.getBlock(multiBlocks[0].cacheKey, true, false, true));
448     assertEquals(null, cache.getBlock(multiBlocks[1].cacheKey, true, false, true));
449 
450     // 4. Insert 3 memory blocks, the remaining 1 single and 2 multi evicted
451     // si:mu:me = 0:0:9
452     cache.cacheBlock(memoryBlocks[6].cacheKey, memoryBlocks[6], true, false);
453     cache.cacheBlock(memoryBlocks[7].cacheKey, memoryBlocks[7], true, false);
454     cache.cacheBlock(memoryBlocks[8].cacheKey, memoryBlocks[8], true, false);
455     // Three evictions, three evicted.
456     assertEquals(9, cache.getStats().getEvictionCount());
457     assertEquals(9, cache.getStats().getEvictedCount());
458     // one oldest single block and two oldest multi blocks evicted
459     assertEquals(null, cache.getBlock(singleBlocks[4].cacheKey, true, false, true));
460     assertEquals(null, cache.getBlock(multiBlocks[2].cacheKey, true, false, true));
461     assertEquals(null, cache.getBlock(multiBlocks[3].cacheKey, true, false, true));
462 
463     // 5. Insert one memory block, the oldest memory evicted
464     // si:mu:me = 0:0:9
465     cache.cacheBlock(memoryBlocks[9].cacheKey, memoryBlocks[9], true, false);
466     // one eviction, one evicted.
467     assertEquals(10, cache.getStats().getEvictionCount());
468     assertEquals(10, cache.getStats().getEvictedCount());
469     // oldest memory block evicted
470     assertEquals(null, cache.getBlock(memoryBlocks[0].cacheKey, true, false, true));
471 
472     // 6. Insert one new single block, itself evicted immediately since
473     //    all blocks in cache are memory-type which have higher priority
474     // si:mu:me = 0:0:9 (no change)
475     cache.cacheBlock(singleBlocks[9].cacheKey, singleBlocks[9]);
476     // one eviction, one evicted.
477     assertEquals(11, cache.getStats().getEvictionCount());
478     assertEquals(11, cache.getStats().getEvictedCount());
479     // the single block just cached now evicted (can't evict memory)
480     assertEquals(null, cache.getBlock(singleBlocks[9].cacheKey, true, false, true));
481   }
482 
483   // test scan resistance
484   @Test
485   public void testScanResistance() throws Exception {
486 
487     long maxSize = 100000;
488     long blockSize = calculateBlockSize(maxSize, 10);
489 
490     LruBlockCache cache = new LruBlockCache(maxSize, blockSize, false,
491         (int)Math.ceil(1.2*maxSize/blockSize),
492         LruBlockCache.DEFAULT_LOAD_FACTOR,
493         LruBlockCache.DEFAULT_CONCURRENCY_LEVEL,
494         0.66f, // min
495         0.99f, // acceptable
496         0.33f, // single
497         0.33f, // multi
498         0.34f, // memory
499         1.2f,  // limit
500         false,
501         16 * 1024 * 1024);
502 
503     CachedItem [] singleBlocks = generateFixedBlocks(20, blockSize, "single");
504     CachedItem [] multiBlocks = generateFixedBlocks(5, blockSize, "multi");
505 
506     // Add 5 multi blocks
507     for (CachedItem block : multiBlocks) {
508       cache.cacheBlock(block.cacheKey, block);
509       cache.getBlock(block.cacheKey, true, false, true);
510     }
511 
512     // Add 5 single blocks
513     for(int i=0;i<5;i++) {
514       cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
515     }
516 
517     // An eviction ran
518     assertEquals(1, cache.getStats().getEvictionCount());
519 
520     // To drop down to 2/3 capacity, we'll need to evict 4 blocks
521     assertEquals(4, cache.getStats().getEvictedCount());
522 
523     // Should have been taken off equally from single and multi
524     assertEquals(null, cache.getBlock(singleBlocks[0].cacheKey, true, false, true));
525     assertEquals(null, cache.getBlock(singleBlocks[1].cacheKey, true, false, true));
526     assertEquals(null, cache.getBlock(multiBlocks[0].cacheKey, true, false, true));
527     assertEquals(null, cache.getBlock(multiBlocks[1].cacheKey, true, false, true));
528 
529     // Let's keep "scanning" by adding single blocks.  From here on we only
530     // expect evictions from the single bucket.
531 
532     // Every time we reach 10 total blocks (every 4 inserts) we get 4 single
533     // blocks evicted.  Inserting 13 blocks should yield 3 more evictions and
534     // 12 more evicted.
535 
536     for(int i=5;i<18;i++) {
537       cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
538     }
539 
540     // 4 total evictions, 16 total evicted
541     assertEquals(4, cache.getStats().getEvictionCount());
542     assertEquals(16, cache.getStats().getEvictedCount());
543 
544     // Should now have 7 total blocks
545     assertEquals(7, cache.getBlockCount());
546 
547   }
548 
549   @Test
550   public void testMaxBlockSize() throws Exception {
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         1024);
566     CachedItem [] tooLong = generateFixedBlocks(10, 1024+5, "long");
567     CachedItem [] small = generateFixedBlocks(15, 600, "small");
568 
569 
570     for (CachedItem i:tooLong) {
571       cache.cacheBlock(i.cacheKey, i);
572     }
573     for (CachedItem i:small) {
574       cache.cacheBlock(i.cacheKey, i);
575     }
576     assertEquals(15,cache.getBlockCount());
577     for (CachedItem i:small) {
578       assertNotNull(cache.getBlock(i.cacheKey, true, false, false));
579     }
580     for (CachedItem i:tooLong) {
581       assertNull(cache.getBlock(i.cacheKey, true, false, false));
582     }
583 
584     assertEquals(10, cache.getStats().getFailedInserts());
585   }
586 
587   // test setMaxSize
588   @Test
589   public void testResizeBlockCache() throws Exception {
590 
591     long maxSize = 300000;
592     long blockSize = calculateBlockSize(maxSize, 31);
593 
594     LruBlockCache cache = new LruBlockCache(maxSize, blockSize, false,
595         (int)Math.ceil(1.2*maxSize/blockSize),
596         LruBlockCache.DEFAULT_LOAD_FACTOR,
597         LruBlockCache.DEFAULT_CONCURRENCY_LEVEL,
598         0.98f, // min
599         0.99f, // acceptable
600         0.33f, // single
601         0.33f, // multi
602         0.34f, // memory
603         1.2f,  // limit
604         false,
605         16 * 1024 * 1024);
606 
607     CachedItem [] singleBlocks = generateFixedBlocks(10, blockSize, "single");
608     CachedItem [] multiBlocks = generateFixedBlocks(10, blockSize, "multi");
609     CachedItem [] memoryBlocks = generateFixedBlocks(10, blockSize, "memory");
610 
611     // Add all blocks from all priorities
612     for(int i=0;i<10;i++) {
613 
614       // Just add single blocks
615       cache.cacheBlock(singleBlocks[i].cacheKey, singleBlocks[i]);
616 
617       // Add and get multi blocks
618       cache.cacheBlock(multiBlocks[i].cacheKey, multiBlocks[i]);
619       cache.getBlock(multiBlocks[i].cacheKey, true, false, true);
620 
621       // Add memory blocks as such
622       cache.cacheBlock(memoryBlocks[i].cacheKey, memoryBlocks[i], true, false);
623     }
624 
625     // Do not expect any evictions yet
626     assertEquals(0, cache.getStats().getEvictionCount());
627 
628     // Resize to half capacity plus an extra block (otherwise we evict an extra)
629     cache.setMaxSize((long)(maxSize * 0.5f));
630 
631     // Should have run a single eviction
632     assertEquals(1, cache.getStats().getEvictionCount());
633 
634     // And we expect 1/2 of the blocks to be evicted
635     assertEquals(15, cache.getStats().getEvictedCount());
636 
637     // And the oldest 5 blocks from each category should be gone
638     for(int i=0;i<5;i++) {
639       assertEquals(null, cache.getBlock(singleBlocks[i].cacheKey, true, false, true));
640       assertEquals(null, cache.getBlock(multiBlocks[i].cacheKey, true, false, true));
641       assertEquals(null, cache.getBlock(memoryBlocks[i].cacheKey, true, false, true));
642     }
643 
644     // And the newest 5 blocks should still be accessible
645     for(int i=5;i<10;i++) {
646       assertEquals(singleBlocks[i], cache.getBlock(singleBlocks[i].cacheKey, true, false, true));
647       assertEquals(multiBlocks[i], cache.getBlock(multiBlocks[i].cacheKey, true, false, true));
648       assertEquals(memoryBlocks[i], cache.getBlock(memoryBlocks[i].cacheKey, true, false, true));
649     }
650   }
651 
652   // test metricsPastNPeriods
653   @Test
654   public void testPastNPeriodsMetrics() throws Exception {
655    double delta = 0.01;
656 
657     // 3 total periods
658     CacheStats stats = new CacheStats("test", 3);
659 
660     // No accesses, should be 0
661     stats.rollMetricsPeriod();
662     assertEquals(0.0, stats.getHitRatioPastNPeriods(), delta);
663     assertEquals(0.0, stats.getHitCachingRatioPastNPeriods(), delta);
664 
665     // period 1, 1 hit caching, 1 hit non-caching, 2 miss non-caching
666     // should be (2/4)=0.5 and (1/1)=1
667     stats.hit(false, true, BlockType.DATA);
668     stats.hit(true, true, BlockType.DATA);
669     stats.miss(false, false, BlockType.DATA);
670     stats.miss(false, false, BlockType.DATA);
671     stats.rollMetricsPeriod();
672     assertEquals(0.5, stats.getHitRatioPastNPeriods(), delta);
673     assertEquals(1.0, stats.getHitCachingRatioPastNPeriods(), delta);
674 
675     // period 2, 1 miss caching, 3 miss non-caching
676     // should be (2/8)=0.25 and (1/2)=0.5
677     stats.miss(true, false, BlockType.DATA);
678     stats.miss(false, false, BlockType.DATA);
679     stats.miss(false, false, BlockType.DATA);
680     stats.miss(false, false, BlockType.DATA);
681     stats.rollMetricsPeriod();
682     assertEquals(0.25, stats.getHitRatioPastNPeriods(), delta);
683     assertEquals(0.5, stats.getHitCachingRatioPastNPeriods(), delta);
684 
685     // period 3, 2 hits of each type
686     // should be (6/12)=0.5 and (3/4)=0.75
687     stats.hit(false, true, BlockType.DATA);
688     stats.hit(true, true, BlockType.DATA);
689     stats.hit(false, true, BlockType.DATA);
690     stats.hit(true, true, BlockType.DATA);
691     stats.rollMetricsPeriod();
692     assertEquals(0.5, stats.getHitRatioPastNPeriods(), delta);
693     assertEquals(0.75, stats.getHitCachingRatioPastNPeriods(), delta);
694 
695     // period 4, evict period 1, two caching misses
696     // should be (4/10)=0.4 and (2/5)=0.4
697     stats.miss(true, false, BlockType.DATA);
698     stats.miss(true, false, BlockType.DATA);
699     stats.rollMetricsPeriod();
700     assertEquals(0.4, stats.getHitRatioPastNPeriods(), delta);
701     assertEquals(0.4, stats.getHitCachingRatioPastNPeriods(), delta);
702 
703     // period 5, evict period 2, 2 caching misses, 2 non-caching hit
704     // should be (6/10)=0.6 and (2/6)=1/3
705     stats.miss(true, false, BlockType.DATA);
706     stats.miss(true, false, BlockType.DATA);
707     stats.hit(false, true, BlockType.DATA);
708     stats.hit(false, true, BlockType.DATA);
709     stats.rollMetricsPeriod();
710     assertEquals(0.6, stats.getHitRatioPastNPeriods(), delta);
711     assertEquals((double)1/3, stats.getHitCachingRatioPastNPeriods(), delta);
712 
713     // period 6, evict period 3
714     // should be (2/6)=1/3 and (0/4)=0
715     stats.rollMetricsPeriod();
716     assertEquals((double)1/3, stats.getHitRatioPastNPeriods(), delta);
717     assertEquals(0.0, stats.getHitCachingRatioPastNPeriods(), delta);
718 
719     // period 7, evict period 4
720     // should be (2/4)=0.5 and (0/2)=0
721     stats.rollMetricsPeriod();
722     assertEquals(0.5, stats.getHitRatioPastNPeriods(), delta);
723     assertEquals(0.0, stats.getHitCachingRatioPastNPeriods(), delta);
724 
725     // period 8, evict period 5
726     // should be 0 and 0
727     stats.rollMetricsPeriod();
728     assertEquals(0.0, stats.getHitRatioPastNPeriods(), delta);
729     assertEquals(0.0, stats.getHitCachingRatioPastNPeriods(), delta);
730 
731     // period 9, one of each
732     // should be (2/4)=0.5 and (1/2)=0.5
733     stats.miss(true, false, BlockType.DATA);
734     stats.miss(false, false, BlockType.DATA);
735     stats.hit(true, true, BlockType.DATA);
736     stats.hit(false, true, BlockType.DATA);
737     stats.rollMetricsPeriod();
738     assertEquals(0.5, stats.getHitRatioPastNPeriods(), delta);
739     assertEquals(0.5, stats.getHitCachingRatioPastNPeriods(), delta);
740   }
741 
742   private CachedItem [] generateFixedBlocks(int numBlocks, int size, String pfx) {
743     CachedItem [] blocks = new CachedItem[numBlocks];
744     for(int i=0;i<numBlocks;i++) {
745       blocks[i] = new CachedItem(pfx + i, size);
746     }
747     return blocks;
748   }
749 
750   private CachedItem [] generateFixedBlocks(int numBlocks, long size, String pfx) {
751     return generateFixedBlocks(numBlocks, (int)size, pfx);
752   }
753 
754   private CachedItem [] generateRandomBlocks(int numBlocks, long maxSize) {
755     CachedItem [] blocks = new CachedItem[numBlocks];
756     Random r = new Random();
757     for(int i=0;i<numBlocks;i++) {
758       blocks[i] = new CachedItem("block" + i, r.nextInt((int)maxSize)+1);
759     }
760     return blocks;
761   }
762 
763   private long calculateBlockSize(long maxSize, int numBlocks) {
764     long roughBlockSize = maxSize / numBlocks;
765     int numEntries = (int)Math.ceil((1.2)*maxSize/roughBlockSize);
766     long totalOverhead = LruBlockCache.CACHE_FIXED_OVERHEAD +
767         ClassSize.CONCURRENT_HASHMAP +
768         (numEntries * ClassSize.CONCURRENT_HASHMAP_ENTRY) +
769         (LruBlockCache.DEFAULT_CONCURRENCY_LEVEL * ClassSize.CONCURRENT_HASHMAP_SEGMENT);
770     long negateBlockSize = (long)(totalOverhead/numEntries);
771     negateBlockSize += LruCachedBlock.PER_BLOCK_OVERHEAD;
772     return ClassSize.align((long)Math.floor((roughBlockSize - negateBlockSize)*0.99f));
773   }
774 
775   private long calculateBlockSizeDefault(long maxSize, int numBlocks) {
776     long roughBlockSize = maxSize / numBlocks;
777     int numEntries = (int)Math.ceil((1.2)*maxSize/roughBlockSize);
778     long totalOverhead = LruBlockCache.CACHE_FIXED_OVERHEAD +
779         ClassSize.CONCURRENT_HASHMAP +
780         (numEntries * ClassSize.CONCURRENT_HASHMAP_ENTRY) +
781         (LruBlockCache.DEFAULT_CONCURRENCY_LEVEL * ClassSize.CONCURRENT_HASHMAP_SEGMENT);
782     long negateBlockSize = totalOverhead / numEntries;
783     negateBlockSize += LruCachedBlock.PER_BLOCK_OVERHEAD;
784     return ClassSize.align((long)Math.floor((roughBlockSize - negateBlockSize)*
785         LruBlockCache.DEFAULT_ACCEPTABLE_FACTOR));
786   }
787 
788   private static class CachedItem implements Cacheable {
789     BlockCacheKey cacheKey;
790     int size;
791 
792     CachedItem(String blockName, int size) {
793       this.cacheKey = new BlockCacheKey(blockName, 0);
794       this.size = size;
795     }
796 
797     /** The size of this item reported to the block cache layer */
798     @Override
799     public long heapSize() {
800       return ClassSize.align(size);
801     }
802 
803     /** Size of the cache block holding this item. Used for verification. */
804     public long cacheBlockHeapSize() {
805       return LruCachedBlock.PER_BLOCK_OVERHEAD
806           + ClassSize.align(cacheKey.heapSize())
807           + ClassSize.align(size);
808     }
809 
810     @Override
811     public int getSerializedLength() {
812       return 0;
813     }
814 
815     @Override
816     public CacheableDeserializer<Cacheable> getDeserializer() {
817       return null;
818     }
819 
820     @Override
821     public void serialize(ByteBuffer destination) {
822     }
823     
824     @Override
825     public BlockType getBlockType() {
826       return BlockType.DATA;
827     }
828 
829   }
830 
831 }
832