Skip to content

Commit 2656de5

Browse files
committed
FileLocking Example
1 parent 5e4da05 commit 2656de5

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

10-File Systems/FileLocking.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.io.*;
2+
import java.nio.channels.*;
3+
4+
public class FileLocking{
5+
public static final boolean EXCLUSIVE = false;
6+
public static final boolean SHARED = true;
7+
8+
public static void main(String args[]) throws IOException {
9+
FileLock sharedLock = null;
10+
FileLock exclusiveLock = null;
11+
12+
try{
13+
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
14+
15+
// get the channel for the file
16+
FileChannel ch = raf.getChannel();
17+
18+
// this locks the first half of the file - exclusive
19+
exclusiveLock = ch.lock(0, raf.length()/2, EXCLUSIVE);
20+
21+
/** Now modify the data **/
22+
23+
// release the lock
24+
exclusiveLock.release();
25+
26+
// this locks the second half of the file - shared
27+
sharedLock = ch.lock(raf.length()/2 + 1, raf.length(), SHARED);
28+
29+
/** Now read the data **/
30+
31+
// release the lock
32+
sharedLock.release();
33+
} catch(java.io.IOException ioe){
34+
System.err.println(ioe);
35+
} finally{
36+
if (exclusiveLock != null) exclusiveLock.release();
37+
if (sharedLock != null) sharedLock.release()
38+
}
39+
}
40+
}

10-File Systems/file.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This is a dummy file.

0 commit comments

Comments
 (0)