Search code examples
javaandroidmemory-mapped-filesswapfile

Moving memory in memory mapped swap file


I'm trying to set up a swap file for bitmaps of different sizes by using the MappedByteBuffer to memory map the file. I want to be able to move memory within this file, so maybe two sub-questions:

  • Is there a way to tell the ByteBuffer to move chunks of memory to another index, or
  • Is it possible to directly access the raw mapped memory to do the moving myself.

Solution

  • Ok, I found a way to do this by using the filechannel that is mapped by the MappedByteBuffer to transfer memory within itself.

    RandomAccessFile raFile = new RandomAccessFile(MyFile, "rw");
    FileChannel fileChannel = raFile.getChannel();
    fileChannel.position(srcPosition);
    fileChannel.transferFrom(fileChannel, dstPosition, count);
    

    This is about 200x faster (to be exact: twice as fast when reading a 1/100 of the dataportion) than reading int by int from the MappedByteBuffer and writing it to duplicate that points to another position in the same file.