-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLockingMappedFiles.java
More file actions
74 lines (61 loc) · 1.99 KB
/
LockingMappedFiles.java
File metadata and controls
74 lines (61 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package io;
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
import java.util.concurrent.*;
/**
* RUN:
* javac io/LockingMappedFiles.java && java io.LockingMappedFiles
*
* OUTPUT:
* Locked: 0 to 50331647
* Locked: 75497471 to 113246206
* Unlocked: 75497471 to 113246206
* Unlocked: 0 to 50331647
*/
public class LockingMappedFiles {
static final int LENGTH = 0x8FFFFFF; // 128 MB
static FileChannel fc;
public static void main(String[] args) {
try {
fc = new RandomAccessFile(new File("test.dat"), "rw").getChannel();
MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
for (int i = 0; i < LENGTH; i++) {
out.put((byte)'x');
}
new LockAndModify(out, 0, 0 + LENGTH/3);
new LockAndModify(out, LENGTH/2, LENGTH/2 + LENGTH/4);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private static class LockAndModify extends Thread {
private ByteBuffer buffer;
private int start, end;
LockAndModify(ByteBuffer mbb, int start, int end) {
this.start = start;
this.end = end;
mbb.limit(end);
mbb.position(start);
buffer = mbb.slice();
start();
}
public void run() {
try {
// exclusive blocking
FileLock fl = fc.lock(start, end, false);
System.out.println("Locked: "+start + " to " + end);
// Change
while (buffer.position() < buffer.limit() - 1) {
buffer.put((byte)(buffer.get() + 1));
}
fl.release();
System.out.println("Unlocked: "+start + " to " + end);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}