I am currently looking into an issue with Logback where the Compressor class is unable to delete a file if I open it in the log file reader glogg. This situation only happens with that program, should I open the file in Notepad.exe no issues arise, so it is somehow related to locking the file or something like that (full reproduction steps exist in the linked repo).
Right now, I need to manually open the glogg program to reproduce the issue, but ideally I would like to just reproduce this using the Java demo program. So far, I have been quite unsuccessful. So I would like to know how to achieve the following:
- Start thread A and thread B
- thread A should write to file X
- when Thread A is doing
File#delete()
on X it should returnfalse
(meaning unsuccessful) - thread B should be the reason for this as it holds on to the file somehow, preventing the delete from being successful
What I have tried out
public void run() {
while (true) {
logDumper.debug(bigString);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] s) {
final Runnable runnable = () -> {
try {
var fileInputStream = new FileInputStream("./test.log");
var file = new File("./test.log");
fileInputStream.readAllBytes();
System.out.println("Size: " + file.length());
final var fc = fileInputStream.getChannel();
// this entire locking thing does not seem to have any effect
final var shared = true; // required to avoid throwing when opening a file as read-only
try (FileLock lock = fc.tryLock(0,file.length(), shared)) {
} catch (NonReadableChannelException| NonWritableChannelException e) {
logger.error("Something happened", e);
fc.close();
}
} catch (IOException e) {
logger.error("Crashed on locking", e);
e.printStackTrace();
}
};
new Thread(runnable).start();
new Main().run();
}