1 package org.apache.commons.jcs.auxiliary.disk.block;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import junit.framework.TestCase;
23
24 /**
25 * Simple tests for the element descriptor
26 * <p>
27 * @author Aaron Smuts
28 */
29 public class BlockDiskElementDescriptorUnitTest
30 extends TestCase
31 {
32 /**
33 * Verify that the memory used per element is reasonable.
34 * <p>
35 * TODO figure out a more precise expectation.
36 * <p>
37 * @throws Exception
38 */
39 public void testMemorySize()
40 throws Exception
41 {
42 // SETUP
43 long memoryBefore = measureMemoryUse();
44 // System.out.println( "Before: " + memoryBefore );
45
46 int numElements = 25000;
47 @SuppressWarnings("unchecked")
48 BlockDiskElementDescriptor<Integer>[] elements = new BlockDiskElementDescriptor[numElements];
49
50 long memoryStart = measureMemoryUse();
51 // System.out.println( "Start: " + memoryStart );
52
53 // DO WORK
54 for ( int i = 0; i < numElements; i++ )
55 {
56 BlockDiskElementDescriptor<Integer> descriptor = new BlockDiskElementDescriptor<Integer>();
57 descriptor.setKey( Integer.valueOf( i ) );
58 descriptor.setBlocks( new int[] { 1, 2 } );
59 elements[i] = descriptor;
60 }
61
62 // VERIFY
63 long memoryEnd = measureMemoryUse();
64 // System.out.println( "End: " + memoryEnd );
65
66 long diff = memoryEnd - memoryStart;
67 // System.out.println( "diff: " + diff );
68
69 long perDiff = diff / numElements;
70 // System.out.println( "per diff: " + perDiff );
71
72 // about 20 bytes each
73 assertTrue( "Too much was used: " + perDiff + " >= 75", perDiff < 75 );
74 }
75
76 /**
77 * Measure memory used by the VM.
78 * @return long
79 * @throws InterruptedException
80 */
81 protected long measureMemoryUse()
82 throws InterruptedException
83 {
84 System.gc();
85 Thread.sleep( 3000 );
86 System.gc();
87 return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
88 }
89 }