-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFileLocking.java
More file actions
37 lines (31 loc) · 870 Bytes
/
FileLocking.java
File metadata and controls
37 lines (31 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package io;
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
import java.util.concurrent.*;
/**
* RUN:
* javac io/FileLocking.java && java io.FileLocking
*
* OUTPUT:
* File locked
* Lock released
*/
public class FileLocking {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream(new File("file.txt"));
FileLock fl = fos.getChannel().tryLock();
if (fl != null) {
System.out.println("File locked");
TimeUnit.MILLISECONDS.sleep(1000);
fl.release();
System.out.println("Lock released");
}
fos.close();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}