How to make the java system release Soft References?

后端 未结 5 1699
慢半拍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:30

    This piece of code forces the JVM to flush all SoftReferences. And it's very fast to do.

    It's working better than the Integer.MAX_VALUE approach, since here the JVM really tries to allocate that much memory.

    try {
        Object[] ignored = new Object[(int) Runtime.getRuntime().maxMemory()];
    } catch (OutOfMemoryError e) {
        // Ignore
    }

    I now use this bit of code everywhere I need to unit test code using SoftReferences.

    Update: This approach will indeed work only with less than 2G of max memory.

    Also, one need to be very careful with SoftReferences. It's so easy to keep a hard reference by mistake that will negate the effect of SoftReferences.

    Here is a simple test that shows it working every time on OSX. Would be interested in knowing if JVM's behavior is the same on Linux and Windows.

    
    for (int i = 0; i < 1000; i++) {
        SoftReference softReference = new SoftReferencelt(new Object());
        if (null == softReference.get()) {
            throw new IllegalStateException("Reference should NOT be null");
        }
    
        try {
            Object[] ignored = new Object[(int) Runtime.getRuntime().maxMemory()];
        } catch (OutOfMemoryError e) {
            // Ignore
        }
    
        if (null != softReference.get()) {
            throw new IllegalStateException("Reference should be null");
        }
    
        System.out.println("It worked!");
    }
        

    提交回复
    热议问题