/*
 * Copyright (c) 2016-2020 chronicle.software
 */

package net.openhft.chronicle.core;

import net.openhft.chronicle.core.io.IOTools;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;

import static org.junit.Assert.assertEquals;

public class CleaningRandomAccessFileTest {

    static int getFDs() {
        if (!OS.isLinux())
            return -1;
        return new File("/proc/self/fd").list().length;
    }

    @Before
    public void cleanUp() {
        System.gc();
        Jvm.pause(100);
    }

    @Test
    public void resourceLeak() throws IOException {
        File tempDir = IOTools.createTempFile("resourceLeak");
        tempDir.mkdir();
        for (int j = 0; j < 50; j++) {
            int files = getFDs();
            if (files > 0) {
//                System.out.println("File descriptors " + files);
                assertEquals(200, files, 200);
            }
            ByteBuffer bb = ByteBuffer.allocateDirect(64);
            for (int i = 0; i < 200; i++) {
                RandomAccessFile file = new CleaningRandomAccessFile(tempDir + "/file" + i, "rw");
                bb.clear();
                file.getChannel().write(bb);
            }
            System.gc();
            Jvm.pause(Jvm.isAzulZing() ? 100 : 10);
        }
    }
}
@@ -758,24 +758,68 @@
 ir.mkdir();%0A
+        int repeat = Jvm.isArm() ? 10 : 50;%0A
         for 
@@ -834,18 +834,22 @@
  0; j %3C 
-50
+repeat
 ; j++) %7B
@@ -1008,16 +1008,27 @@
 tEquals(
+%22j: %22 + j, 
 200, fil
@@ -1356,82 +1356,504 @@
     
-System.gc();%0A            Jvm.pause(Jvm.isAzulZing() ? 100 : 10);%0A        %7D
+long start = System.currentTimeMillis();%0A            System.gc();%0A            for (int i = 0; i %3C 40; i++) %7B%0A                Jvm.pause(20);%0A                if (getFDs() %3C 400) %7B%0A                    double time = (System.currentTimeMillis() - start) / 1e3;%0A                    if (time %3E 0.1)%0A                        System.out.println(%22resourceLeak() - Took %22 + time + %22 seconds.%22);%0A                    break;%0A                %7D%0A            %7D%0A        %7D%0A        IOTools.deleteDirWithFiles(tempDir);
 %0A   

Handle slow cleanup of files.