[英]FileChannel.write on Linux produces lots of garbage, but not on Mac
我试图限制我的日志库产生的垃圾量,所以我编写了一个测试来向我展示FileChannel.write创建了多少内存。 下面的代码在我的Mac上分配了ZERO内存,但是在我的Linux机箱(Ubuntu 10.04.1 LTS)上创建了大量的垃圾,触发了GC。 FileChannels应该是快速和轻量级的。 是否有一个JRE版本在Linux上做得更好?
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存在内存分配问题。
我在Ubuntu 10.04上,我可以确认你的观察。 我的JDK是:
java version "1.6.0_20"
OpenJDK Runtime Environment (IcedTea6 1.9.9) (6b20-1.9.9-0ubuntu1~10.04.2)
OpenJDK 64-Bit Server VM (build 19.0-b09, mixed mode)
解决方案是使用DirectByteBuffer
,而不是由数组支持的HeapByteBuffer
。
如果我没记错的话,这是一个非常古老的“功能”,可以追溯到JDK 1.4:如果你没有给一个Channel
提供DirectByteBuffer
,那么就会分配一个临时的DirectByteBuffer
并在写入之前复制内容。 您基本上看到这些临时缓冲区在JVM中挥之不去。
以下代码适用于我:
File file = new File("fileChannelTest.log");
FileOutputStream fos = new FileOutputStream(file);
FileChannel fileChannel = fos.getChannel();
ByteBuffer bb1 = ByteBuffer.wrap("This is a log line to test!\n".getBytes());
ByteBuffer bb2 = ByteBuffer.allocateDirect(bb1.remaining());
bb2.put(bb1).flip();
bb2.mark();
long freeMemory = Runtime.getRuntime().freeMemory();
for (int i = 0; i < 1000000; i++) {
bb2.reset();
fileChannel.write(bb2);
}
System.out.println("Memory allocated: " + (freeMemory - Runtime.getRuntime().freeMemory()));
仅供参考: HeapByteBuffer
的副本被接受
sun.nio.ch.IOUtil.write(FileDescriptor, ByteBuffer, long, NativeDispatcher, Object)
它使用sun.nio.ch.Util.getTemporaryDirectBuffer(int)
。 这反过来使用SoftReference
实现了一个DirectByteBuffer
的每个线程池。 所以没有真正的内存泄漏, 只有浪费。 叹
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.