Java文件锁定 [英] Java File Locking
问题描述
我有几个线程(其中一些由进程X产生,其他由进程Y产生,等等),每个线程都需要写入文件MyFile
.但是,如果Thread T1
首先开始写入MyFile
,则Thread T2
开始写入时,它需要等待T1
释放文件 ,以便它可以读取内容用Thread T1
编写的.换句话说,每个线程都会有一个finalizeThread
方法,如下所示:
I have several threads (some of which are spawned by Process X, others by Process Y, et cetera), and each thread needs to write to a file MyFile
. However, if Thread T1
starts writing to MyFile
first, then, when Thread T2
starts writing, it needs to wait for T1
to release the file, so that it can read the contents that were written in Thread T1
. In other words, each thread would have a finalizeThread
method, like so:
private void finalizeThread() {
File f = new File("MyFile.dat");
f.createNewFile(); // atomically creates the file, if it doesn't exist
locked_section {
readContentsFromFile(f); // read contents if some other thread already modified the file
modifyContentsFromFile(f); // modify
writeFile(f); // write, so that new threads can see the content modified by this thread
}
}
我的问题是:如何完成以上代码中的locked_section
?我正在研究FileLock
类,但是在Javadoc中它说文件锁代表整个Java虚拟机持有.它们不适合控制同一内部的多个线程对文件的访问虚拟机." .
My question is: How can I accomplish the locked_section
in the above code? I was looking into the FileLock
class, but it says in the Javadoc that "File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.".
推荐答案
如果仅从您的程序访问文件,则同步锁对象是可以的.但是,如果您想保护文件在使用过程中不被其他程序更改,则可以在示例).正如文字所言,请记住,在某些操作系统上,如果程序不检查现有文件锁,它们仍然可以更改文件.
If the file is only accessed from your program, the synchronized lock object is okay. But if you want to protect the file from being changed by other programs while you're working on it, you can use Java's file locking features in java.nio.channels.FileLock
(example). As the text says, mind that on some operating systems, programs can still change files if they don't check for an existing file lock.
这篇关于Java文件锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!