乐趣区

关于java:Guava-规避OOM需要注意的点

gvaua cache 应用堆内存,因而使用不当会呈现 OOM 问题

放弃下限
private static Cache<String, Object> cache = CacheBuilder.newBuilder().maximumSize(5).build();

public static void main(String[] args) {for (int i = 0; i < 10; i++) {cache.put(String.valueOf(i), i);
    }
    System.out.println(cache.asMap());
}

输入后果

{6=6, 9=9, 8=8, 7=7, 5=5}
设置有效期
// 当写入速度大于生效速度时,会 OOM,因而应同时设置下限
private static Cache<String, Object> cache = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.SECONDS).build();

public static void main(String[] args) throws InterruptedException {for (int i = 0; i < 10; i++) {cache.put(String.valueOf(i), i);
    }
    Thread.sleep(3000);
    System.out.println(cache.asMap());
}

输入后果

{}
设置冷数据有效期
// 当写入速度大于生效速度时,会 OOM,因而应同时设置下限
private static Cache<String, Object> cache = CacheBuilder.newBuilder().expireAfterAccess(2, TimeUnit.SECONDS).build();

public static void main(String[] args) throws InterruptedException {for (int i = 0; i < 10; i++) {cache.put(String.valueOf(i), i);
    }
    Thread.sleep(1000);
    cache.getIfPresent("5");
    Thread.sleep(1000);
    System.out.println(cache.asMap());
}

输入后果

{5=5}
设置援用规定
private static Cache<String, Object> cache = CacheBuilder.newBuilder().build();

public static void main(String[] args) throws InterruptedException {while (true) {cache.put(UUID.randomUUID().toString(), new String());
    }
}

输入后果

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.nio.CharBuffer.wrap(CharBuffer.java:373)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:265)

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"

调整后则不会 OOM

private static Cache<String, Object> cache = CacheBuilder.newBuilder().weakKeys().build();

CacheBuilder.weakKeys():应用弱援用存储键。当键没有其它(强或软)援用时,缓存项能够被垃圾回收。

CacheBuilder.weakValues():应用弱援用存储值。当值没有其它(强或软)援用时,缓存项能够被垃圾回收。

CacheBuilder.softValues():应用软援用存储值。软援用只有在响应内存须要时,才依照全局最近起码应用的程序回收。

退出移动版