/* Force releasing SoftReferences */ try { final List memhog = new LinkedList(); while(true) { memhog.add(new long[102400]); } } catch(final OutOfMemoryError e) { /* At this point all SoftReferences have been released - GUARANTEED. */ } /* continue the test here */
@Test public void shouldNotHoldReferencesToObject() { final SoftReference reference = new SoftReference( ... ); // Sanity check assertThat(reference.get(), not(equalTo(null))); // Force an OoM try { final ArrayList allocations = new ArrayList(); int size; while( (size = Math.min(Math.abs((int)Runtime.getRuntime().freeMemory()),Integer.MAX_VALUE))>0 ) allocations.add( new Object[size] ); } catch( OutOfMemoryError e ) { // great! } // Verify object has been garbage collected assertThat(reference.get(), equalTo(null)); }
将参数-Xmx设置为非常小的值。
准备你的软参考
尽可能多地创建对象。 每次询问对象,直到它再次从服务器询问对象。
这是我的小测试。 根据需要进行修改。
@Test public void testSoftReference() throws Exception { Set s = new HashSet(); SoftReference sr = new SoftReference(new Object()); int i = 0; while (true) { try { s.add(new Object[1000]); } catch (OutOfMemoryError e) { // ignore } if (sr.get() == null) { System.out.println("Soft reference is cleared. Success!"); break; } i++; System.out.println("Soft reference is not yet cleared. Iteration " + i); } }