Is createTempFile thread-safe?

对着背影说爱祢 提交于 2019-12-22 07:01:57

问题


I'm using Java 6.

Is it possible that two threads calling createTempFile (of the class java.io.File) get the same temp file?


回答1:


Best way to get your answer is to look at the source code. At first there isn't any synchronization in createTempFile, but to generate the temp file name, it is using SecureRandom which is ThreadSafe. Then unless you are really unlucky, your file will always get a different name.

On top of that, createTempFile implementation is looping, generating new file name, until the file has been created. The file creation of course is delegated to the native file system operation which we may assume is threadsafe..




回答2:


The method File.createTempFile actually creates the file. A thread will only return a file name it alone created. (you can check the source code to see this)




回答3:


The possibility exists, but it is so remote that considering it is a waste of effort... and if an application needs to worry about this possibility for maintaining its correct functioning, then I would take that as a sign that there is something fishing with its design.



来源:https://stackoverflow.com/questions/4702537/is-createtempfile-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!