我有 2 个线程同时访问同一个大文件(.txt)。
第一个线程正在从文件中读取。第二个线程正在写入文件。
两个线程都访问同一个块,例如(start:0,blocksize:10),但具有不同的通道和缓冲区实例
读者:
{
int BLOCK_SIZE = 10;
byte[] bytesArr = new byte[BLOCK_SIZE];
File file = new File("/db.txt");
RandomAccessFile randomFile = new RandomAccessFile(file, "r");
FileChannel channel = randomFile.getChannel();
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_ONLY, 0, BLOCK_SIZE);
map.get(bytesArr , 0, BLOCK_SIZE);
channel.close();
}
作家:
{
int BLOCK_SIZE = 10;
File file = new File("/db.txt");
RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomFile.getChannel();
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, BLOCK_SIZE);
map.put(bytesToWrite);
channel.close();
}
我知道如果两者同时开始,我会得到重叠异常!但是我想知道的是,重叠到底发生在什么时候?我的意思是什么时候发生“锁定”?示例:假设作者首先获得访问权限,然后如果读者尝试访问,那么在什么时候有可能?:
FileChannel channel = randomFile.getChannel();
// 1- can reader access here?
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, BLOCK_SIZE);
// 2- can reader access here?
map.put(bytesToWrite);
// 3- can reader access here?
channel.close();
// 4- can reader access here?
1、2、3 还是 4?
没有4是肯定的,因为通道被关闭了!其他点呢?
谢谢!