gpt4 book ai didi

java - 如何找出哪个线程在java中锁定文件?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:19:13 25 4
gpt4 key购买 nike

我正在尝试删除我程序中的另一个线程之前处理过的文件。

我无法删除该文件,但我不确定如何确定哪个线程可能正在使用该文件。

那么我如何找出哪个线程在 java 中锁定文件?

最佳答案

我没有一个直接的答案(我也不认为有一个,这是在操作系统级别( native )而不是 JVM 级别控制的)而且我也没有真正看到值(value)答案(一旦发现它是哪个线程,您仍然无法以编程方式关闭文件),但我认为您还不知道无法删除通常是在文件仍处于打开状态时造成的。当您显式调用 Closeable#close() 时可能会发生这种情况在 InputStreamOutputStreamReaderWriter 上,它们围绕 File 构建有问题。

基本演示:

public static void main(String[] args) throws Exception {
File file = new File("c:/test.txt"); // Precreate this test file first.
FileOutputStream output = new FileOutputStream(file); // This opens the file!
System.out.println(file.delete()); // false
output.close(); // This explicitly closes the file!
System.out.println(file.delete()); // true
}

换句话说,确保在您的整个 Java IO 内容中,代码在使用后正确地关闭资源。 The normal idiom是在 the try-with-resources statement 中执行此操作,这样您就可以确定无论如何都会释放资源,即使出现 IOException 也是如此。例如

try (OutputStream output = new FileOutputStream(file)) {
// ...
}

任何 InputStreamOutputStreamReaderWriter 执行此操作,等任何工具 AutoCloseable ,您将自己打开(使用new关键字)。

这在某些实现上在技术上是不需要的,例如 ByteArrayOutputStream,但为了清楚起见,只需在所有地方坚持 close-in-finally 习惯用法以避免误解和重构错误.

如果您还没有使用 Java 7 或更新版本,请改用下面的 try-finally 习语。

OutputStream output = null;
try {
output = new FileOutputStream(file);
// ...
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}

希望这有助于确定您的特定问题的根本原因。

关于java - 如何找出哪个线程在java中锁定文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2177553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com