【发布时间】:2011-09-19 17:19:49
【问题描述】:
我试图限制我的日志库产生的垃圾量,所以我编写了一个测试来显示 FileChannel.write 创建了多少内存。下面的代码在我的 Mac 上分配零内存,但在我的 Linux 机器(Ubuntu 10.04.1 LTS)上创建了大量垃圾,触发了 GC。 FileChannels 应该是快速和轻量级的。有没有在 Linux 上改进的 JRE 版本?
File file = new File("fileChannelTest.log");
FileOutputStream fos = new FileOutputStream(file);
FileChannel fileChannel = fos.getChannel();
ByteBuffer bb = ByteBuffer.wrap("This is a log line to test!\n".getBytes());
bb.mark();
long freeMemory = Runtime.getRuntime().freeMemory();
for (int i = 0; i < 1000000; i++) {
bb.reset();
fileChannel.write(bb);
}
System.out.println("Memory allocated: " + (freeMemory - Runtime.getRuntime().freeMemory()));
我的 JRE 的详细信息如下:
java version "1.6.0_19"
Java(TM) SE Runtime Environment (build 1.6.0_19-b04)
Java HotSpot(TM) 64-Bit Server VM (build 16.2-b04, mixed mode)
更新到:
java version "1.6.0_27"
Java(TM) SE Runtime Environment (build 1.6.0_27-b07)
Java HotSpot(TM) 64-Bit Server VM (build 20.2-b06, mixed mode)
而且效果很好。 :-|
好吧,现在我们知道 FileChannelImpl 的早期版本存在内存分配问题。
【问题讨论】:
-
当我使用 java 1.6.0_26 在 linux 上运行它时,它说分配的内存是“0”。
-
这里相同:但我在 11.04。抱歉,我没有要测试的 10.04。
-
顺便说一句,我能够编写一个日志库,在日志记录到磁盘时分配零内存。更多细节在这里:mentalog.soliveirajr.com
标签: java garbage-collection nio bytebuffer filechannel