新的File("...")是否锁定文件? [英] Does new File("...") lock the file?

查看:68
本文介绍了新的File("...")是否锁定文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到new File("path")并没有在磁盘上实际创建文件.尽管在API中有这样的说法:

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

此类的实例可能表示也可能不是实际的文件系统 对象,例如文件或目录.如果它确实表示这样的对象,则该对象驻留在分区中.分区是文件系统存储的特定于操作系统的部分.单个存储设备(例如,物理磁盘驱动器,闪存,CD-ROM)可能包含多个分区.

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

例如,thread1来到这里,创建一个实例并开始进行操作.同时thread2中断了它,创建了具有相同名称的实例 (myfile.zip),并执行了一些其他操作.之后,他们将保存文件.

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.

推荐答案

否,文件不保持锁定,对于您描述的模式也不安全.您应该将文件锁定或保留在某些包装器类中.

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.

这篇关于新的File("...")是否锁定文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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