【发布时间】:2015-07-16 11:39:39
【问题描述】:
我有 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是肯定的,因为通道被关闭了!其他点呢?
谢谢!
【问题讨论】:
-
我看到你的代码没有锁定。
-
为什么要使用多个线程?您的用例的一些概述将有助于我们提供建议。一般来说,除非发生了非常特殊的情况,否则我建议只使用一个线程进行 I/O。
-
@ChrisK,我可以给你一个用例,但是你熟悉 JSF ManagedBeans 吗?
-
从我遥远的过去,是的。不过要温柔,我很容易瘀伤。
-
@ChrisK,对不起,我说了什么让你生气了?
标签: java multithreading memory-mapped-files mappedbytebuffer