Skip to content

Instantly share code, notes, and snippets.

@avisagie
Created May 26, 2015 06:05
Show Gist options
  • Save avisagie/e788a49ba66ca9761f63 to your computer and use it in GitHub Desktop.
Save avisagie/e788a49ba66ca9761f63 to your computer and use it in GitHub Desktop.
Test java closing mapped files and GC
package com.company;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
* Opens a file, maps a chunk, closes. Expect to see many open filehandles until it GCs.
* http://mail-archives.apache.org/mod_mbox/kafka-users/201503.mbox/%3C54F40DEA.4020009@gmail.com%3E
*/
public class Main {
public static void main(String[] args) throws Exception {
File f = new File("mapfile.dat");
if (!f.exists()) {
System.out.println("Creating " + f.getCanonicalPath());
FileOutputStream o = new FileOutputStream(f);
o.write(new byte[16 << 10]);
o.close();
}
int total = 0;
while (true) {
for (int ii = 0; ii < 100; ii++) {
++total;
FileInputStream in = new FileInputStream(f);
FileChannel ch = in.getChannel();
MappedByteBuffer b = ch.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
in.close();
}
System.out.println("Created " + total + " mappings");
Thread.sleep(1000);
//System.gc();
//System.runFinalization();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment