1 16 package org.apache.commons.collections.map; 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.BulkTest; 24 25 32 public class TestReferenceMap extends AbstractTestIterableMap { 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 "3.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 198 199 200 public void testPurgeValues() throws Exception { 201 Object key = new Object (); 203 Object value = new Object (); 204 205 WeakReference keyReference = new WeakReference (key); 206 WeakReference valueReference = new WeakReference (value); 207 208 Map testMap = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.HARD, true); 209 testMap.put(key, value); 210 211 assertEquals("In map", value, testMap.get(key)); 212 assertNotNull("Weak reference released early (1)", keyReference.get()); 213 assertNotNull("Weak reference released early (2)", valueReference.get()); 214 215 key = null; 217 value = null; 218 219 int iterations = 0; 220 int bytz = 2; 221 while(true) { 222 System.gc(); 223 if(iterations++ > 50){ 224 fail("Max iterations reached before resource released."); 225 } 226 testMap.isEmpty(); 227 if( 228 keyReference.get() == null && 229 valueReference.get() == null) { 230 break; 231 232 } else { 233 byte[] b = new byte[bytz]; 235 bytz = bytz * 2; 236 } 237 } 238 } 239 240 private static void gc() { 241 try { 242 byte[][] tooLarge = new byte[1000000000][1000000000]; 244 fail("you have too much RAM"); 245 } catch (OutOfMemoryError ex) { 246 System.gc(); } 248 } 249 250 } 251 | Popular Tags |