Source code: org/activemq/io/util/MemoryBoundedMessageCacheTest.java
1 /**
2 *
3 * Copyright 2004 Protique Ltd
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 **/
18
19 package org.activemq.io.util;
20 import junit.framework.TestCase;
21
22 import org.activemq.message.ActiveMQMessage;
23
24 /**
25 * MemoryBoundedQueueTest
26 *
27 * @version $Revision: 1.1.1.1 $
28 */
29 public class MemoryBoundedMessageCacheTest extends TestCase {
30
31 private static final int TEST_INSTANCE_SIZE = 2048;
32
33 private final MemoryBoundedObjectManager memoryManager = new MemoryBoundedObjectManager("testmanager", 1024 * 1024);
34
35 public void testMemoryGrowth() throws Exception {
36
37 // Setup space for 2 messages.
38 MemoryBoundedMessageCache cache = new MemoryBoundedMessageCache(memoryManager);
39 memoryManager.setValueLimit(TEST_INSTANCE_SIZE*2);
40 assertEquals(0, memoryManager.getTotalMemoryUsedSize());
41
42 ActiveMQMessage msg = new ActiveMQMessage();
43 msg.setMemoryUsage(TEST_INSTANCE_SIZE);
44 cache.put("test", msg);
45
46 ActiveMQMessage msg2 = new ActiveMQMessage();
47 msg2.setMemoryUsage(TEST_INSTANCE_SIZE);
48 cache.put("test2", msg2);
49
50 // Cache had space so the messages sill should be there.
51 assertNotNull( cache.get("test") );
52 assertNotNull( cache.get("test2") );
53
54 assertTrue(0 < memoryManager.getTotalMemoryUsedSize());
55
56 cache.remove("test");
57 cache.remove("test2");
58 assertEquals(0, memoryManager.getTotalMemoryUsedSize());
59
60 }
61
62 public void testMemoryLimiting() throws Exception {
63
64 // Setup space for only 1 message.
65 MemoryBoundedMessageCache cache = new MemoryBoundedMessageCache(memoryManager);
66 memoryManager.setValueLimit(TEST_INSTANCE_SIZE/2);
67 assertEquals(0, memoryManager.getTotalMemoryUsedSize());
68
69 for( int i=0; i < 10; i++ ) {
70 ActiveMQMessage msg = new ActiveMQMessage();
71 msg.setMemoryUsage(TEST_INSTANCE_SIZE);
72 cache.put("first:"+i, msg);
73 }
74
75 ActiveMQMessage msg = new ActiveMQMessage();
76 msg.setMemoryUsage(TEST_INSTANCE_SIZE);
77 cache.put("last", msg);
78
79 // Only the last message should be in the cache.
80 assertNull( cache.get("first:9") );
81 assertNotNull( cache.get("last") );
82
83 assertTrue(0 < memoryManager.getTotalMemoryUsedSize());
84
85 cache.remove("last");
86 assertEquals(0, memoryManager.getTotalMemoryUsedSize());
87
88 }
89
90 }