public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException { //省略参数检查
long addr = -1; int ti = -1; try { begin(); ti = threads.add(); if (!isOpen()) returnnull;
long mapSize; int pagePosition; //加锁,保证线程安全 synchronized (positionLock) { long filesize; do { filesize = nd.size(fd); } while ((filesize == IOStatus.INTERRUPTED) && isOpen()); if (!isOpen()) returnnull; //如果映射范围超出文件的大小且不可写,则抛出异常 if (filesize < position + size) { // Extend file size if (!writable) { thrownew IOException("Channel not open for writing " + "- cannot extend file to required size"); } int rv; //填充文件 do { rv = nd.allocate(fd, position + size); } while ((rv == IOStatus.INTERRUPTED) && isOpen()); if (!isOpen()) returnnull; }
pagePosition = (int)(position % allocationGranularity); long mapPosition = position - pagePosition; mapSize = size + pagePosition; try { // If map0 did not throw an exception, the address is valid addr = map0(imode, mapPosition, mapSize); } catch (OutOfMemoryError x) { // An OutOfMemoryError may indicate that we've exhausted // memory so force gc and re-attempt map System.gc(); try { Thread.sleep(100); } catch (InterruptedException y) { Thread.currentThread().interrupt(); } try { addr = map0(imode, mapPosition, mapSize); } catch (OutOfMemoryError y) { // After a second OOME, fail thrownew IOException("Map failed", y); } } } // synchronized
// On Windows, and potentially other platforms, we need an open // file descriptor for some mapping operations. FileDescriptor mfd; try { mfd = nd.duplicateForMapping(fd); } catch (IOException ioe) { unmap0(addr, mapSize); throw ioe; }
MappedByteBuffer在处理大文件时的确性能很高,但也存在一些问题,如内存占用、文件关闭不确定,被其打开的文件只有在垃圾回收的才会被关闭,而且这个时间点是不确定的。 javadoc中也提到:A mapped byte buffer and the file mapping that it represents remain valid until the buffer itself is garbage-collected.