Hope someone can shed some light into what I'm doing wrong.
I have a DataLoader class that creates a FileInputStream. Since FileInputStream implements Closeable, I create that instance as part of the try block.
I then pass the newly created stream to a DataManager class. This class opens a file channel and reads data into a singleton class, storing all data into memory blocks. Since FileChannel also implements Closeable, I also instanciate it in the try block
I then invoke this code from a single thread to check every now if there are any filechanges, and when this happens, a new instance of DataLoader is created to rebuild the memory blocks. But this constantly fails due to file locking. This code is part of a Java 1.8 standard application, running on windows 10. Am I assuming wrongly that both file channel and file inputstream close? I added code to invoke the close method in both classes, but with no success.
Any help would be greatly appreciated. Thanks in advance.
public class DataManager {
public DataManager(FileInputStream in) throws IOException {
fromInputStream(in);
}
public final void fromInputStream(FileInputStream in) throws IOException {
try (FileChannel ch = in.getChannel()) {
MappedByteBuffer mb = ch.map(MapMode.READ_ONLY, ch.position(), ch.size());
readData(mb); //reads mapped buffer into a byte array, e.g.: mb.get(barray, 0, 1000);
}
}
}
public class DataLoader {
public DataLoader(File binFile) throws FileNotFoundException, IOException {
try (FileInputStream in = new FileInputStream(binFile)) {
DataManager d = new DataManager(in);
} catch (Exception e) {
LOG.error("Something went wrong while loading data.", e);
}
}
}
As suggested in the comments, the issue relies on windows being somewhat stringent regarding the use of FileChannel. I replaced all FileChannel related code with InputStream and the locking behavior disappeared.