1 package org.apache.directmemory.ehcache;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23
24 import net.sf.ehcache.CacheException;
25 import net.sf.ehcache.CacheManager;
26 import net.sf.ehcache.Ehcache;
27 import net.sf.ehcache.Element;
28
29 import org.junit.Assert;
30 import org.junit.Test;
31
32 public class EHCacheTest
33 {
34
35 @Test
36 public void testPutRetreive()
37 {
38 CacheManager cacheManager = CacheManager.getInstance();
39 Ehcache ehcache = cacheManager.getEhcache( "testCache" );
40
41 ehcache.put( new Element( "testKey", "testValue" ) );
42 stats( ehcache );
43 Assert.assertEquals( "testValue", ehcache.get( "testKey" ).getObjectValue() );
44 }
45
46 @Test
47 public void testSizing()
48 {
49 CacheManager cacheManager = CacheManager.getInstance();
50 Ehcache ehcache = cacheManager.getEhcache( "testCache" );
51 for ( int i = 0; i < 30000; i++ )
52 {
53 if ( ( i % 1000 ) == 0 )
54 {
55 System.out.println( "heatbeat " + i );
56 stats( ehcache );
57 }
58 ehcache.put( new Element( i, new byte[1024] ) );
59 }
60 stats( ehcache );
61 Assert.assertTrue( true );
62 }
63
64 @Test
65 public void testOffHeapExceedMemory()
66 throws IOException
67 {
68 CacheManager cacheManager = CacheManager.getInstance();
69 Ehcache ehcache = cacheManager.getEhcache( "testCache" );
70 Element element = null;
71 try
72 {
73 for ( int i = 0; i < 3000000; i++ )
74 {
75 if ( ( i % 1000 ) == 0 )
76 {
77 System.out.println( "heatbeat 2 " + i );
78 stats( ehcache );
79 }
80 element = new Element( i, new byte[1024] );
81 ehcache.put( element );
82 }
83 Assert.fail( "CacheException expected for DirectMemory OffHeap Memory Exceeded" );
84 }
85 catch ( CacheException e )
86 {
87 stats( ehcache );
88 Assert.assertTrue( "CacheException expected for DirectMemory OffHeap Memory Exceeded", true );
89 }
90
91 }
92
93 private void stats( Ehcache ehcache )
94 {
95 System.out.println( "OnHeapSize=" + ehcache.calculateInMemorySize() + ", OnHeapElements="
96 + ehcache.getMemoryStoreSize() );
97 System.out.println( "OffHeapSize=" + ehcache.calculateOffHeapSize() + ", OffHeapElements="
98 + ehcache.getOffHeapStoreSize() );
99 System.out.println( "DiskStoreSize=" + ehcache.calculateOnDiskSize() + ", DiskStoreElements="
100 + ehcache.getDiskStoreSize() );
101 }
102
103 }