1

I noticed this weird thing that opened FileChannel object works even after linked file is deleted while a file channel is in use. I have created 15GB test file and following program reads 100MB of file content consequently per second.

    Path path = Paths.get("/home/elbek/tmp/file.txt");
    FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ);
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 1024);
    while (true) {
        int read = fileChannel.read(byteBuffer);
        if (read < 0) {
            break;
        }
        Thread.sleep(10);
        byteBuffer.clear();
        System.out.println(fileChannel.position());
    }
    fileChannel.close();

After program runs ~5 seconds (it has read 0.5GB) I delete the file from the file system and expect an error to be thrown after a few reads, but the program goes on and reads the file till the end, I was initially thinking maybe it is being served from file cache and made file huge so it won't fit into cache, 15GB is big enough I think not to fit into it. Anyways, how OS is serving read requests while the file itself is not there anymore? The OS I am testing this is Fedora.

Thanks.

user207421
  • 305,947
  • 44
  • 307
  • 483
Elbek
  • 3,434
  • 6
  • 37
  • 49
  • 1
    This is fundamental Unix file semantics. – chrylis -cautiouslyoptimistic- Jun 23 '17 at 04:16
  • Adn therefore nothing to do with `FileChannel` or Java. The same would apply to a file you were `cat`-ing. – user207421 Jun 23 '17 at 04:26
  • After quick search I found, A mapped byte buffer and the file mapping that it represents remain valid until the buffer itself is garbage-collected. Try calling. Try System.gc() and test if the fie is still working or not – Fady Saad Jun 23 '17 at 04:30
  • @chrylis, that explains it. here is the more complete answer: https://stackoverflow.com/questions/22246397/why-file-is-accessible-after-deleting-in-unix – Elbek Jun 23 '17 at 04:31

0 Answers0