我有两个线程同时访问同一个大文件(.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?
第四个不确定,因为通道已关闭!其他几点怎么样?
谢谢!