1 16 package org.apache.commons.collections; 17 18 import java.lang.ref.WeakReference ; 19 import java.util.Map ; 20 21 import junit.framework.Test; 22 23 import org.apache.commons.collections.map.AbstractTestMap; 24 25 32 public class TestReferenceMap extends AbstractTestMap { 33 34 public TestReferenceMap(String testName) { 35 super(testName); 36 } 37 38 public static Test suite() { 39 return BulkTest.makeSuite(TestReferenceMap.class); 40 } 41 42 public static void main(String args[]) { 43 String [] testCaseName = { TestReferenceMap.class.getName() }; 44 junit.textui.TestRunner.main(testCaseName); 45 } 46 47 public Map makeEmptyMap() { 48 ReferenceMap map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.WEAK); 49 return map; 50 } 51 52 public boolean isAllowNullKey() { 53 return false; 54 } 55 56 public boolean isAllowNullValue() { 57 return false; 58 } 59 60 public String getCompatibilityVersion() { 61 return "2.1"; 62 } 63 64 public void testNullHandling() { 66 resetFull(); 67 assertEquals(null, map.get(null)); 68 assertEquals(false, map.containsKey(null)); 69 assertEquals(false, map.containsValue(null)); 70 assertEquals(null, map.remove(null)); 71 assertEquals(false, map.entrySet().contains(null)); 72 assertEquals(false, map.keySet().contains(null)); 73 assertEquals(false, map.values().contains(null)); 74 try { 75 map.put(null, null); 76 fail(); 77 } catch (NullPointerException ex) {} 78 try { 79 map.put(new Object (), null); 80 fail(); 81 } catch (NullPointerException ex) {} 82 try { 83 map.put(null, new Object ()); 84 fail(); 85 } catch (NullPointerException ex) {} 86 } 87 88 154 155 156 public void testPurgeValues() throws Exception { 157 Object key = new Object (); 159 Object value = new Object (); 160 161 WeakReference keyReference = new WeakReference (key); 162 WeakReference valueReference = new WeakReference (value); 163 164 Map testMap = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.HARD, true); 165 testMap.put(key, value); 166 167 assertEquals("In map", value, testMap.get(key)); 168 assertNotNull("Weak reference released early (1)", keyReference.get()); 169 assertNotNull("Weak reference released early (2)", valueReference.get()); 170 171 key = null; 173 value = null; 174 175 int iterations = 0; 176 int bytz = 2; 177 while(true) { 178 System.gc(); 179 if(iterations++ > 50){ 180 fail("Max iterations reached before resource released."); 181 } 182 testMap.isEmpty(); 183 if( 184 keyReference.get() == null && 185 valueReference.get() == null) { 186 break; 187 188 } else { 189 byte[] b = new byte[bytz]; 191 bytz = bytz * 2; 192 } 193 } 194 } 195 196 private static void gc() { 197 try { 198 byte[][] tooLarge = new byte[1000000000][1000000000]; 200 fail("you have too much RAM"); 201 } catch (OutOfMemoryError ex) { 202 System.gc(); } 204 } 205 } 206 | Popular Tags |