OnJava8-Examples/newio/LockingMappedFiles.java

61 lines
1.7 KiB
Java
Raw Normal View History

2015-11-03 12:00:44 -08:00
// newio/LockingMappedFiles.java
2020-10-07 13:35:40 -06:00
// (c)2020 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Locking portions of a mapped file
2015-06-15 17:47:35 -07:00
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
public class LockingMappedFiles {
static final int LENGTH = 0x8FFFFFF; // 128 MB
static FileChannel fc;
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
2017-01-21 16:29:16 -08:00
fc = new RandomAccessFile("test.dat", "rw")
.getChannel();
MappedByteBuffer out = fc.map(
FileChannel.MapMode.READ_WRITE, 0, LENGTH);
2015-06-15 17:47:35 -07:00
for(int i = 0; i < LENGTH; i++)
out.put((byte)'x');
new LockAndModify(out, 0, 0 + LENGTH/3);
2017-01-21 16:29:16 -08:00
new LockAndModify(
out, LENGTH/2, LENGTH/2 + LENGTH/4);
2015-06-15 17:47:35 -07:00
}
private static class LockAndModify extends Thread {
private ByteBuffer buff;
private int start, end;
LockAndModify(ByteBuffer mbb, int start, int end) {
this.start = start;
this.end = end;
mbb.limit(end);
mbb.position(start);
buff = mbb.slice();
start();
}
@Override
public void run() {
try {
// Exclusive lock with no overlap:
FileLock fl = fc.lock(start, end, false);
2016-01-25 18:05:55 -08:00
System.out.println(
"Locked: "+ start +" to "+ end);
2015-06-15 17:47:35 -07:00
// Perform modification:
while(buff.position() < buff.limit() - 1)
buff.put((byte)(buff.get() + 1));
fl.release();
2016-01-25 18:05:55 -08:00
System.out.println(
"Released: " + start + " to " + end);
2015-06-15 17:47:35 -07:00
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2016-07-22 14:45:35 -06:00
Locked: 75497471 to 113246206
Locked: 0 to 50331647
2015-06-15 17:47:35 -07:00
Released: 75497471 to 113246206
Released: 0 to 50331647
2015-09-07 11:44:36 -06:00
*/