背景
了解java的nio,因为在看到lucene的MappedByteBuffer , 所以想了解一下nio的内容 nio 主要包括三个内容:
- Buffer
- Selector
- Channel
Buffer
ByteBuffer
- MappedByteBuffer
- HeapByteBuffer
- DirectByteBuffer
例子
简单的例子:
@Test
public void fileChannel()
throws IOException {
try (FileChannel fc = FileChannel.open(Paths.get("ccc.cc"),StandardOpenOption.WRITE , StandardOpenOption.READ ,StandardOpenOption.CREATE) ) {
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1);
byte b = 97;
bb.put(0 ,b );
fc.write(bb);
var charset = Charset.defaultCharset();
System.out.println( "res" + charset.decode(bb).toString());
}
}
其实调用:
@ForceInline
public void put$Type$(Scope scope, Object base, long offset, $type$ value) {
try {
put$Type$Internal(scope, base, offset, value);
} catch (Scope.ScopedAccessError ex) {
throw new IllegalStateException("This segment is already closed");
}
}
@ForceInline @Scoped
private void put$Type$Internal(Scope scope, Object base, long offset, $type$ value) {
try {
if (scope != null) {
scope.checkValidState();
}
UNSAFE.put$Type$(base, offset, value);
} finally {
Reference.reachabilityFence(scope);
}
}
最后写在这里
void put(T x) {
GuardUnsafeAccess guard(_thread);
*addr() = normalize_for_write(x);
}
整个流程就是:
mmap返回的是一个指针 ,MappedByteBuffer 调用UNSAFE.put
方法直接修改堆外内存的值,不经过堆