How to make the java system release Soft References?

后端 未结 5 1698
慢半拍i
慢半拍i 2020-12-05 11:06

I\'m going to use a SoftReference-based cache (a pretty simple thing by itself). However, I\'ve came across a problem when writing a test for it.

The objective of th

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 11:47

    An improvement that will work for more than 2G max memory. It loops until an OutOfMemory error occurs.

    @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));
    
    }
    

提交回复
热议问题