FileLockManager implements LockManager { @Override public CloseLock lockOrFail(Path path) throws IOException { Path lockPath = path.resolve("lock"); try ( Owner<FileChannel, IOException> channelOwner = own(FileChannel.open(lockPath, READ, WRITE, CREATE), IOException.class); Owner<FileLock, IOException> fileLockOwner = own(channelOwner.borrow().tryLock(), IOException.class) ) { if (fileLockOwner.borrow() == null) { throw new IOException("File lock already held: " + path); } return new FileCloseLock(channelOwner.release(), fileLockOwner.release()); } }  @Override CloseLock lockOrFail(Path path);  }
@Test public void lockDoesNotExist() throws Exception { Path directory = temporaryFolder.newFolder().toPath(); FileLockManager lockManager = new FileLockManager(); try (CloseLock closeLock = lockManager.lockOrFail(directory)) { assertNotNull(closeLock); } }
@Test public void lockExists() throws Exception { Path directory = temporaryFolder.newFolder().toPath(); Path lockFile = directory.resolve("lock"); Files.createFile(lockFile); FileLockManager lockManager = new FileLockManager(); try (CloseLock closeLock = lockManager.lockOrFail(directory)) { assertNotNull(closeLock); } }
@Test(expected = OverlappingFileLockException.class) public void locked() throws Exception { Path directory = temporaryFolder.newFolder().toPath(); FileLockManager lockManager = new FileLockManager(); try (CloseLock closeLock = lockManager.lockOrFail(directory)) { assertNotNull(closeLock); lockManager.lockOrFail(directory); } }