我有一个java类,它使用System.GC()来计算内存使用量。但是,当我运行findbugs时,它总是报告错误的行号。 问题1:我使用intellij findbugs插件以及findbugs本机GUI运行此操作。结果相同。我在这里做错了吗?
util.MemoryTestBench.lotsOfGC()强制进行垃圾收集;除了在基准测试代码中,这是非常可疑的 类:MemoryTestBench(util) 行:35 - 35 ====>这是Thread.sleep(100)????????
要处理的死店 类:MemoryTestBench(util) 行:23 - 23 ====>返回usedMemory() - prevUsedMemory ?????
问题2:如何抑制错误DM_GC?我尝试了@SuppressWarnings,但没有用。
测试代码如下:
package util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
public class MemoryTestBench {
@SuppressWarnings (value = "DM_GC",
justification = "call GC to measure memory size")
public static long calculateMemoryUsage(ObjectFactory factory) {
Object handle = factory.makeObject();
long prevUsedMemory = usedMemory();
handle = null;
lotsOfGC();
prevUsedMemory = usedMemory();
handle = factory.makeObject();
lotsOfGC();
return usedMemory() - prevUsedMemory;
}
private static long usedMemory() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
private static void lotsOfGC() {
for (int i = 0; i < 20; i++) {
System.gc();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void showMemoryUsage(ObjectFactory factory) {
long mem = calculateMemoryUsage(factory);
System.out.println(
factory.getClass().getSimpleName() + " produced " +
factory.makeObject().getClass().getSimpleName() +
" which took " + mem + " bytes");
}
public static void main(String[] args) {
showMemoryUsage(new BigConcurrentHashMapFactory());
}
}
答案 0 :(得分:0)
您应该在 lotsOfGC 方法之前放置 @SuppressWarnings ,而不是在 calculateMemoryUsage
之前