如何在Java中以线程安全的方式使用mkdirs?
在经历了 mkdirs() 的问题并浏览了互联网之后,我得到的印象是 mkdirs() 存在线程安全问题。
当多个线程可能尝试创建类似的文件结构时,有没有办法确保正确创建目录?
谢谢
(就我而言,我将在 Android 上使用它)
After experiencing issues with mkdirs() and poking around the interwebs, I get the impression that there are thread safety issues with mkdirs().
Is there a way to ensure the directories are properly created when it is possible that multiple threads might be trying to create similar file structures?
Thanks
(In my case I will be using this on Android)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不确定 Android 是否支持并发包,但我的看法是:
如果目录已经存在,该方法会提前返回。如果它不存在,则只有一个线程会尝试创建它。
I'm not sure if Android supports the concurrent package but here is my take:
The method returns early if the directory already exists. If it doesn't exist, only one thread will try to create it.
在序列化所有内容的工作线程中完成所有目录创建。您可以使用
Looper
和Handler
来轻松地将调用 mkdirs 的Runnables
发布到工作线程。创建完目录后,您可以在处理完最后发布的Runnable
后调用 Looper.quit() 来结束线程。Looper
的文档有示例代码表明这是多么微不足道的事情。Do all your directory creation in a worker thread that serializes everything. You can use a
Looper
and aHandler
to make it easy to postRunnables
that call mkdirs to your worker thread. When you're done making directories, you can call Looper.quit() to end the thread after it processes the last postedRunnable
. The documentation forLooper
has sample code that shows how near to trivial this is to do.一种可能的解决方案是 MkDirService(如下所示),它只保证一个实例并在其自己的线程中运行。利用BlockingQueue。
首先是服务:
测试:
One possible solution would be a MkDirService (illustrated below) that guarantees only one instance and runs in it's own thread. Making use of BlockingQueue.
First the Service:
The the Test:
好吧,我知道这已经有一段时间不活跃了,但我想也许有一个简单的解决方案。您在该问题的评论中链接的文章似乎表明唯一的问题是目录未被创建。解决方案是这样做:
然而,这似乎效率低下,并且仍然可能存在问题。那么,为什么不简单地这样做:
简单,但有效。
编辑:经过一番思考,该示例可能会滞后并可能导致线程锁定。因此,这可能是一个更好的主意:
当然,只有当您处于可能导致线程锁定的线程中,并且只要不是高优先级情况时,才建议这样做。只是把这个放在那里。
Okay, I know this has been inactive for a while, but I thought perhaps there was a simple solution. The article you linked in the comments on the question seems to indicate that the only problem is directories not being created. The solution there was to do this:
However, that seems inefficient and can still have problems. So, why not simply do this:
Simple, but it works.
EDIT: After thinking a bit, that example may lag to oblivion and could cause thread lock. So, this might be a better idea:
Of course, that would only be recommended if you're in a thread that could cause thread lock, and as long as it's not a high-priority situation. Just putting this out there.
即使这个线程有点旧,我想知道以下解决方案是否有问题:
Eaven if this thread is a bit older I wonder if there is somethink wrong with the following solution: