java文件锁定,Java文件锁定

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

}

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值