I am trying to limit the amount of garbage produced by my log library, so I coded a test to show me how much memory is FileChannel.write creating. The code below allocates ZERO memory on my Mac, but creates tons of garbage on my Linux box (Ubuntu 10.04.1 LTS), triggering the GC. FileChannels are supposed to be fast and lightweight. Is there a JRE version where this was made better on 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()));
The details of my JRE are below:
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)
Updated to:
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)
And it worked fine. :-|
Well, so now we know that earlier versions of FileChannelImpl have a memory allocation problem.