我注意到java.io
和java.nio
隨機訪問文件的實現與處理FileLocks
的方式略有不同。隨機訪問文件FileLock:java.io vs. java.nio
看起來好像(在Windows上)java.io
爲您提供強制性文件鎖定,並且java.nio
分別向您提供諮詢文件鎖定。強制性文件鎖意味着該鎖適用於所有進程,並且適用於遵循相同鎖定協議的良好行爲進程的建議。
如果我運行以下示例,我可以手動刪除*.nio
文件,而*.io
文件拒絕刪除。
import java.io.*;
import java.lang.management.ManagementFactory;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
public class NioIoLock {
public static void main(String[] args) throws IOException, InterruptedException {
String workDir = System.getProperty("user.dir");
FileChannel channelIo, channelNio;
FileLock lockIo, lockNio;
// use io
{
String fileName = workDir
+ File.separator
+ ManagementFactory.getRuntimeMXBean().getName()
+ ".io";
File lockFile = new File(fileName);
lockFile.deleteOnExit();
RandomAccessFile file = new RandomAccessFile(lockFile, "rw");
channelIo = file.getChannel();
lockIo = channelIo.tryLock();
if (lockIo != null) {
channelIo.write(ByteBuffer.wrap("foobar".getBytes("UTF-8")));
}
}
// use nio
{
Path workDirPath = Paths.get(workDir);
Path file = workDirPath.resolve(
Paths.get(ManagementFactory.getRuntimeMXBean().getName() + ".nio"));
// open/create test file
channelNio = FileChannel.open(
file, StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
// lock file
lockNio = channelNio.tryLock();
if (lockNio != null) {
channelNio.write(ByteBuffer.wrap("foobar".getBytes("UTF-8")));
}
}
// do not release locks for some time
Thread.sleep(10000);
// release io lock and channel
if (lockIo != null && lockIo.isValid()) {
lockIo.release();
}
channelIo.close();
// release nio lock and channel
if (lockNio != null && lockNio.isValid()) {
lockNio.release();
}
channelNio.close();
}
}
這是有原因嗎?這兩者甚至被認爲是替代品還是它們意味着無限期地共存?
將'SYNC,DSYNC'添加到nio版本會有所作爲嗎?那麼這將是一個性能考慮。 –
加入'SYNC,DSYNC'沒有什麼區別 – starikoff