Java无缘无故地锁定文件 [英] Java keeps lock on files for no apparent reason

查看:92
本文介绍了Java无缘无故地锁定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管在finally子句中关闭了流,但在使用Java时我似乎总是遇到清理问题。 File.delete()无法删除文件,Windows资源管理器也失败。运行System.gc()有时会有所帮助,但是没有什么可以帮助终止VM,这不是一种选择。

Despite closing streams in finally clauses I seem to constantly run into cleaning up problems when using Java. File.delete() fails to delete files, Windows Explorer fails too. Running System.gc() helps sometimes but nothing short of terminating the VM helps consistently and that is not an option.

有没有人有任何其他想法我可以尝试?我在Windows XP上使用Java 1.6。

Does anyone have any other ideas I could try? I use Java 1.6 on Windows XP.

更新:删除了FLAC代码示例,如果我将代码隔离,代码就可以工作。

UPDATE: FLAC code sample removed, the code worked if I isolated it.

更新:
更多信息,这发生在Apache Tomcat,Commons FileUpload用于上传文件,可能是罪魁祸首,我也使用Runtime.exec()在一个单独的进程中执行LAME来编码文件,但这似乎不太可能导致这一点,因为ProcessExplorer清楚地表明java.exe对文件有一个RW锁定,LAME终止正常。

UPDATE: More info, this happens in Apache Tomcat, Commons FileUpload is used to upload the file and could be the culprit, also I use Runtime.exec() to execute LAME in a separate process to encode the file, but that seems unlikely to cause this since ProcessExplorer clearly indicates that java.exe has a RW lock on the file and LAME terminates fine.

更新:我正在使用假设缺少close()或close()不会在我的代码或外部库中调用。我找不到它!

UPDATE: I am working with the assumption that there is a missing close() or a close() that does not get called somewhere in my code or external library. I just can't find it!

推荐答案

您发布的代码看起来不错 - 它不应该导致您描述的问题。我了解到你只发布了一段代码 - 你能尝试将这部分提取到一个单独的程序中,运行它并查看问题是否仍然存在?
我的猜测是代码中有一些其他地方用新的FileInputStream(路径); 并且没有正确关闭流。当您尝试删除文件时,您可能只是在这里看到结果。

The code you posted looks good - it should not cause the issues you are describing. I understand you posted just a piece of the code you have - can you try extracting just this part to a separate program, run it and see if the issue still happens? My guess is that there is some other place in the code that does new FileInputStream(path); and does not close the stream properly. You might be just seeing the results here when you try to delete the file.

这篇关于Java无缘无故地锁定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆