OnJava8-Examples/newio/FileLocking.java
2016-01-25 18:05:55 -08:00

28 lines
735 B
Java

// newio/FileLocking.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
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");
}
}
}
}
/* Output:
Locked File
Released Lock
*/