OnJava8-Examples/io/FileLocking.java

25 lines
585 B
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// io/FileLocking.java
2015-06-15 17:47:35 -07:00
// <20>2015 MindView LLC: see Copyright.txt
import java.nio.channels.*;
import java.util.concurrent.*;
import java.io.*;
public class FileLocking {
public static void main(String[] args) throws Exception {
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-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Locked File
Released Lock
2015-09-07 11:44:36 -06:00
*/