如何在Java中的线程安全的方式使用mkdirs? [英] How to use mkdirs in a thread safe manner in Java?

查看:754
本文介绍了如何在Java中的线程安全的方式使用mkdirs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在遇到问题mkdirs()和周围的interwebs戳,我得到的IM pression有与mkdirs线程安全问题()。

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?

感谢

(在我来说,我将使用这个在Android)

(In my case I will be using this on Android)

推荐答案

好吧,我知道这已经闲置了一段时间,但我想也许有一个简单的解决方案。你对这个问题的评论链接的文章似乎表明,唯一的问题是的没有的所创建的目录。解决的办法有做到这一点:

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:

if (!f.mkdirs()) {
    f.mkdirs();
}

不过,这似乎效率不高,仍然可能会出现问题。那么,为什么不能简单地做到这一点:

However, that seems inefficient and can still have problems. So, why not simply do this:

while (!f.mkdirs()) {}

很简单,但它的工作原理。

Simple, but it works.

编辑:思考了一下之后,这个例子可能会滞后于遗忘,并可能导致螺纹锁。因此,这可能是一个更好的主意:

After thinking a bit, that example may lag to oblivion and could cause thread lock. So, this might be a better idea:

while (!f.mkdirs()) { Thread.yield(); }

当然,如果你是在一个线程中,可能会导致螺纹锁,只要它不是一个高优先级的情况下,只会被推荐。只是把这个在那里。

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.

这篇关于如何在Java中的线程安全的方式使用mkdirs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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