Skip to content

Instantly share code, notes, and snippets.

@dstuebe
Created July 18, 2019 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstuebe/28fdbed439a6a73d8b2e08f11fea38d3 to your computer and use it in GitHub Desktop.
Save dstuebe/28fdbed439a6a73d8b2e08f11fea38d3 to your computer and use it in GitHub Desktop.
Example java program that heavily utilizes mmap/page cache
/**
* MIT License
*
* Copyright (c) 2019 Upserve, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.io.*;
import java.nio.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.LongStream;
public class PageCache implements Closeable {
/*
Run with: java PageCache {file path} {nMaps} {mReads}
where file path is the path to the output file, nMaps is the number of 4mb mapped byte buffers to create in the file
and mReads is the number of times to read an int value (all ones!) from each map.
*/
public static void main(String args[]){
try(PageCache pageCache = new PageCache(Paths.get(args[0]))) {
pageCache.setMaps(Integer.parseInt(args[1]));
System.out.println("Read ints from maps");
long sum = pageCache.readMaps(Long.parseLong(args[2]));
System.out.println("Read sum:" + sum);
} catch (IOException e) {
throw new UncheckedIOException("Failed to map page cache!", e);
}
}
private OpenOption[] openOptions;
private FileChannel.MapMode mapMode;
private FileChannel channel;
private MappedByteBuffer[] mappedByteBuffers = new MappedByteBuffer[0];
private long MAP_SIZE = 4 * 1024 * 1024;
ByteBuffer directBuffer;
public PageCache(Path filePath) {
openOptions = new OpenOption[]{StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE};
mapMode = FileChannel.MapMode.READ_WRITE;
try {
channel = FileChannel.open(filePath, openOptions);
} catch (IOException e) {
throw new UncheckedIOException("failed to open file: " + filePath, e);
}
int[] iarray = new int[ (int) MAP_SIZE / 4];
Arrays.fill(iarray, 1);
directBuffer = ByteBuffer.allocate((int) MAP_SIZE);
directBuffer.asIntBuffer().put(iarray);
}
public void setMaps(int nmaps) {
mappedByteBuffers = new MappedByteBuffer[nmaps];
LongStream
.range(0, nmaps)
.parallel()
.forEach(val -> {
MappedByteBuffer buffer = null;
try {
buffer = channel.map(mapMode, val * MAP_SIZE, MAP_SIZE);
} catch (IOException e) {
throw new UncheckedIOException("Unable to map page", e);
}
mappedByteBuffers[(int) val] = buffer;
buffer.put(directBuffer.duplicate().position(0));
if (val % 100 == 0) System.out.println("Filled Map Number: " + val);
});
}
public long readMaps(long ntimes) {
return Arrays.stream(mappedByteBuffers)
.parallel()
.flatMapToInt(
mappedByteBuffer -> ThreadLocalRandom.current()
.ints(ntimes, 0, (int) MAP_SIZE / 4)
.map(val -> mappedByteBuffer.getInt(val * 4)) //.peek(val -> System.out.println("Rand val: " + val))
).sum();
}
@Override
public void close() throws IOException {
if (channel.isOpen()) channel.close();
}
}
@dstuebe
Copy link
Author

dstuebe commented Jul 18, 2019

Compile with:
javac PageCache.java

Run with:
java PageCache foo.file 200 100

This will create an 800mb file composed of 200 4mb mapped byte buffers and then read 100 int values from each buffer. Both steps occur in parallel.

@dstuebe
Copy link
Author

dstuebe commented Mar 13, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment