2015-04-20 15:36:01 -07:00
|
|
|
|
//: io/FileLocking.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-04-20 15:36:01 -07:00
|
|
|
|
import java.nio.channels.*;
|
|
|
|
|
import java.util.concurrent.*;
|
|
|
|
|
import java.io.*;
|
|
|
|
|
|
|
|
|
|
public class FileLocking {
|
|
|
|
|
public static void main(String[] args) throws Exception {
|
2015-05-05 14:05:39 -07:00
|
|
|
|
try (FileOutputStream fos = new FileOutputStream("file.txt")) {
|
|
|
|
|
FileLock fl = fos.getChannel().tryLock();
|
|
|
|
|
if(fl != null) {
|
|
|
|
|
System.out.println("Locked File");
|
|
|
|
|
TimeUnit.MILLISECONDS.sleep(100);
|
|
|
|
|
fl.release();
|
|
|
|
|
System.out.println("Released Lock");
|
|
|
|
|
}
|
2015-04-20 15:36:01 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} /* Output:
|
|
|
|
|
Locked File
|
|
|
|
|
Released Lock
|
|
|
|
|
*///:~
|