Does new File(“…”) lock the file?

寵の児 提交于 2020-01-04 02:50:06

问题


I read that new File("path") doesn't physically create a file on disk. Though in the API it is said:

Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions.

So I'm curious if it is safe to have such code in multithreaded environment:

File file = new File( "myfile.zip" );
// do some operations with file (fill it with content)
file.saveSomewhere(); // just to denote that I save it after several operations

For example, thread1 comes here, creates an instance and starts doing operations. Meanwhile thread2 interrupts it, creates its instance with the same name (myfile.zip) and does some other operations. After that they consequently save the file.

I need to be sure that they don't work with the same file and the last thread saving the file overwrites the previous one.


回答1:


No, File does not keep a lock and is not safe for the pattern you describe. You should either lock or keep the file in some wrapper class.

If you would provide a little bit more of your code, somebody can certainly help you find a suitable pattern.




回答2:


Certainly the lines you commented will not thread-safe, you will have to protect them with a mutex or a monitor. The gold rule is: every time you have to write on something in a multithread context, it's necessary to protect that region to grant the thread-safeness (Bernstein conditions).

I'm not sure if the statement you propose requires to be protected too as i never used that command, but i thought this could be helpful to someone else too.



来源:https://stackoverflow.com/questions/21828275/does-new-file-lock-the-file

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