Java Reference
In-Depth Information
}
The static sleep() method in the Thread class causes the current thread to sleep for the number of mil-
liseconds specified by the argument. While the current thread is sleeping, other threads can execute, so
whoever has a lock on our file has a chance to release it.
Here's the code for the complete example:
import java.nio.file.*;
import java.nio.channels.*;
import java.io.IOException;
import java.nio.*;
public class LockingPrimesRead {
public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("primes.bin");
final int PRIMECOUNT = 6;
final int LONG_BYTES = 8;
ByteBuffer buf = ByteBuffer.allocate(LONG_BYTES*PRIMECOUNT);
long[] primes = new long[PRIMECOUNT];
try (FileChannel inCh =
(FileChannel)(Files.newByteChannel(file))){
int primesRead = 0;
FileLock inLock = null;
// File reading loop
while(true) {
int tryLockCount = 0;
// Loop to get a lock on the file region you want to read
while(true) {
inLock = inCh.tryLock(inCh.position(), buf.remaining(),
true);
if(inLock != null) { // If you have a lock
System.out.println("\nAcquired file lock.");
break;
// exit the loop
}
if(++tryLockCount >= 100) { // If you've tried too often
System.out.printf("Failed to acquire lock after %d
tries." +
"Terminating...%n",
tryLockCount);
System.exit(1);
// end the program
}
Search WWH ::




Custom Search