File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed
Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 1+ This is a dummy file.
You can’t perform that action at this time.
0 commit comments