Here are the examples of the java api class java.nio.channels.FileLock taken from open source projects.
1. FileSystemBinaryStoreTest#shouldCreateFileLock()
Project: modeshape
File: FileSystemBinaryStoreTest.java
File: FileSystemBinaryStoreTest.java
@Test public void shouldCreateFileLock() throws IOException { File tmpFile = File.createTempFile("foo", "bar"); File tmpDir = tmpFile.getParentFile(); tmpFile.delete(); assertThat(tmpDir.exists(), is(true)); assertThat(tmpDir.canRead(), is(true)); assertThat(tmpDir.canWrite(), is(true)); assertThat(tmpDir.isDirectory(), is(true)); File lockFile = new File(tmpDir, "lock"); lockFile.createNewFile(); RandomAccessFile raf = new RandomAccessFile(lockFile, "rw"); FileLock fileLock = raf.getChannel().lock(); fileLock.release(); assertThat(lockFile.exists(), is(true)); lockFile.delete(); }
2. FileHandle#unlock()
Project: mina-sshd
File: FileHandle.java
File: FileHandle.java
public void unlock(long offset, long length) throws IOException { FileChannel channel = getFileChannel(); long size = (length == 0L) ? channel.size() - offset : length; FileLock lock = null; for (Iterator<FileLock> iterator = locks.iterator(); iterator.hasNext(); ) { FileLock l = iterator.next(); if ((l.position() == offset) && (l.size() == size)) { iterator.remove(); lock = l; break; } } if (lock == null) { throw new SftpException(SftpConstants.SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK, "No mtahcing lock found on range [" + offset + "-" + (offset + length)); } lock.release(); }
3. JimfsFileChannelTest#testLock()
Project: jimfs
File: JimfsFileChannelTest.java
File: JimfsFileChannelTest.java
@Test public void testLock() throws IOException { FileChannel channel = channel(regularFile(10), READ, WRITE); assertNotNull(channel.lock()); assertNotNull(channel.lock(0, 10, false)); assertNotNull(channel.lock(0, 10, true)); assertNotNull(channel.tryLock()); assertNotNull(channel.tryLock(0, 10, false)); assertNotNull(channel.tryLock(0, 10, true)); FileLock lock = channel.lock(); assertTrue(lock.isValid()); lock.release(); assertFalse(lock.isValid()); }
4. NativeFSLockFactory#main()
Project: graphhopper
File: NativeFSLockFactory.java
File: NativeFSLockFactory.java
public static void main(String[] args) throws IOException { // trying FileLock mechanics in different processes File file = new File("tmp.lock"); file.createNewFile(); FileChannel channel = new RandomAccessFile(file, "r").getChannel(); boolean shared = true; FileLock lock1 = channel.tryLock(0, Long.MAX_VALUE, shared); System.out.println("locked " + lock1); System.in.read(); System.out.println("release " + lock1); lock1.release(); }
5. TestFileSystem#testSimpleExpandTruncateSize()
Project: ThriftyPaxos
File: TestFileSystem.java
File: TestFileSystem.java
private void testSimpleExpandTruncateSize() throws Exception { String f = "memFS:" + getBaseDir() + "/fs/test.data"; FileUtils.createDirectories("memFS:" + getBaseDir() + "/fs"); FileChannel c = FileUtils.open(f, "rw"); c.position(4000); c.write(ByteBuffer.wrap(new byte[1])); FileLock lock = c.tryLock(); c.truncate(0); if (lock != null) { lock.release(); } c.close(); FileUtils.deleteRecursive("memFS:", false); }
6. FilePathRetryOnInterrupt#reLock()
Project: ThriftyPaxos
File: FilePathRetryOnInterrupt.java
File: FilePathRetryOnInterrupt.java
private void reLock() throws IOException { if (lock == null) { return; } try { lock.base.release(); } catch (IOException e) { } FileLock l2 = channel.tryLock(lock.position(), lock.size(), lock.isShared()); if (l2 == null) { throw new IOException("Re-locking failed"); } lock.base = l2; }
7. Fetcher#getLock()
Project: tez
File: Fetcher.java
File: Fetcher.java
private FileLock getLock() throws OverlappingFileLockException, InterruptedException, IOException { File lockFile = localFs.pathToFile(new Path(lockPath, host + ".lock")); final boolean created = lockFile.createNewFile(); if (created == false && !lockFile.exists()) { // bail-out cleanly return null; } // invariant - file created (winner writes to this file) // caveat: closing lockChannel does close the file (do not double close) // JDK7 - TODO: use AsynchronousFileChannel instead of RandomAccessFile FileChannel lockChannel = new RandomAccessFile(lockFile, "rws").getChannel(); FileLock xlock = null; xlock = lockChannel.tryLock(0, Long.MAX_VALUE, false); if (xlock != null) { return xlock; } lockChannel.close(); return null; }
8. RTreeTest#testSaveFileException()
Project: rtree
File: RTreeTest.java
File: RTreeTest.java
// @Test(expected = IOException.class) public void testSaveFileException() throws IOException { FileLock lock = null; RandomAccessFile file = null; try { String filename = "target/locked.png"; File f = new File(filename); f.createNewFile(); file = new RandomAccessFile(f, "rw"); lock = file.getChannel().lock(); RTree.create().visualize(600, 600).save(filename, "PNG"); } finally { try { lock.release(); file.close(); } catch (IOException e) { e.printStackTrace(); } } }
9. StaxWorkBookTest#testRead()
Project: pentaho-kettle
File: StaxWorkBookTest.java
File: StaxWorkBookTest.java
@Test public void testRead() throws Exception { FileLock lock = null; RandomAccessFile randomAccessFile = null; try { readData(); File fileAfterRead = new File("testfiles/sample-file.xlsx"); randomAccessFile = new RandomAccessFile(fileAfterRead, "rw"); FileChannel fileChannel = randomAccessFile.getChannel(); lock = fileChannel.tryLock(); // check that we could lock file assertTrue(lock.isValid()); } finally { if (lock != null) { lock.release(); } if (randomAccessFile != null) { randomAccessFile.close(); } } }
10. PoiWorkBookTest#testResourceFree()
Project: pentaho-kettle
File: PoiWorkBookTest.java
File: PoiWorkBookTest.java
@Test public void testResourceFree() throws Exception { FileLock lock = null; RandomAccessFile randomAccessFile = null; try { readData(); File fileAfterRead = new File("testfiles/sample-file.xlsx"); randomAccessFile = new RandomAccessFile(fileAfterRead, "rw"); FileChannel fileChannel = randomAccessFile.getChannel(); lock = fileChannel.tryLock(); // check that we could lock file assertTrue(lock.isValid()); } finally { if (lock != null) { lock.release(); } if (randomAccessFile != null) { randomAccessFile.close(); } } }
11. FileHandle#lock()
Project: mina-sshd
File: FileHandle.java
File: FileHandle.java
public void lock(long offset, long length, int mask) throws IOException { FileChannel channel = getFileChannel(); long size = (length == 0L) ? channel.size() - offset : length; FileLock lock = channel.tryLock(offset, size, false); if (lock == null) { throw new SftpException(SftpConstants.SSH_FX_BYTE_RANGE_LOCK_REFUSED, "Overlapping lock held by another program on range [" + offset + "-" + (offset + length)); } synchronized (locks) { locks.add(lock); } }
12. Stream#putContents()
Project: jphp
File: Stream.java
File: Stream.java
@Signature({ @Arg("path"), @Arg("data"), @Arg(value = "mode", optional = @Optional("w+")) }) public static Memory putContents(Environment env, Memory... args) throws Throwable { Stream stream = create(env, args[0].toString(), args[2].toString()); FileLock lock = null; try { if (stream instanceof FileStream) { lock = ((FileStream) stream).getAccessFile().getChannel().lock(); } try { return env.invokeMethod(stream, "write", args[1]); } finally { if (lock != null) { lock.release(); } } } finally { env.invokeMethod(stream, "close"); } }
13. FileLocking#main()
Project: java-core-learning-example
File: FileLocking.java
File: FileLocking.java
public static void main(String[] args) throws IOException, InterruptedException { // ????? FileOutputStream fos = new FileOutputStream("data.txt"); // ?????????????????File FileLock fl = fos.getChannel().lock(); if (fl != null) { System.out.println("Locked File"); TimeUnit.MICROSECONDS.sleep(100); // ?????? fl.release(); System.out.println("Release Lock"); } }
14. FileChannelImpl#addLock()
Project: j2objc
File: FileChannelImpl.java
File: FileChannelImpl.java
/** * Add a new pending lock to the manager. Throws an exception if the lock * would overlap an existing lock. Once the lock is acquired it remains in * this set as an acquired lock. */ private synchronized void addLock(FileLock lock) throws OverlappingFileLockException { long lockEnd = lock.position() + lock.size(); for (FileLock existingLock : locks) { if (existingLock.position() > lockEnd) { // cannot overlap). break; } if (existingLock.overlaps(lock.position(), lock.size())) { throw new OverlappingFileLockException(); } } locks.add(lock); }
15. FileChannelImpl#lock()
Project: j2objc
File: FileChannelImpl.java
File: FileChannelImpl.java
public final FileLock lock(long position, long size, boolean shared) throws IOException { checkOpen(); FileLock resultLock = null; { boolean completed = false; try { begin(); resultLock = basicLock(position, size, shared, true); completed = true; } finally { end(completed); } } return resultLock; }
16. PatchTest#testValidatingNonAccessibleFiles()
Project: intellij-community
File: PatchTest.java
File: PatchTest.java
@Test public void testValidatingNonAccessibleFiles() throws Exception { Patch patch = createPatch(); File f = new File(myOlderDir, "Readme.txt"); try (FileOutputStream s = new FileOutputStream(f, true); FileLock ignored = s.getChannel().lock()) { String message = UtilsTest.mIsWindows ? System.getProperty("java.vm.name").contains("OpenJDK") ? "Locked by: OpenJDK Platform binary" : "Locked by: Java(TM) Platform SE binary" : ValidationResult.ACCESS_DENIED_MESSAGE; ValidationResult.Option option = UtilsTest.mIsWindows ? ValidationResult.Option.KILL_PROCESS : ValidationResult.Option.IGNORE; assertThat(patch.validate(myOlderDir, TEST_UI)).containsOnly(new ValidationResult(ValidationResult.Kind.ERROR, "Readme.txt", ValidationResult.Action.UPDATE, message, option)); } }
17. DataStorage#isConversionNeeded()
Project: hadoop-hdfs
File: DataStorage.java
File: DataStorage.java
public boolean isConversionNeeded(StorageDirectory sd) throws IOException { File oldF = new File(sd.getRoot(), "storage"); if (!oldF.exists()) return false; // check the layout version inside the storage file // Lock and Read old storage file RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws"); FileLock oldLock = oldFile.getChannel().tryLock(); try { oldFile.seek(0); int oldVersion = oldFile.readInt(); if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION) return false; } finally { oldLock.release(); oldFile.close(); } return true; }
18. DataStorage#isConversionNeeded()
Project: hadoop-common
File: DataStorage.java
File: DataStorage.java
public boolean isConversionNeeded(StorageDirectory sd) throws IOException { File oldF = new File(sd.getRoot(), "storage"); if (!oldF.exists()) return false; // check the layout version inside the storage file // Lock and Read old storage file RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws"); FileLock oldLock = oldFile.getChannel().tryLock(); try { oldFile.seek(0); int oldVersion = oldFile.readInt(); if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION) return false; } finally { oldLock.release(); oldFile.close(); } return true; }
19. DataStorage#isConversionNeeded()
Project: hadoop-20
File: DataStorage.java
File: DataStorage.java
public boolean isConversionNeeded(StorageDirectory sd) throws IOException { File oldF = new File(sd.getRoot(), "storage"); if (!oldF.exists()) return false; // check the layout version inside the storage file // Lock and Read old storage file RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws"); FileLock oldLock = oldFile.getChannel().tryLock(); try { oldFile.seek(0); int oldVersion = oldFile.readInt(); if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION) return false; } finally { oldLock.release(); oldFile.close(); } return true; }
20. GitMaterialTest#shouldThrowExceptionWhenWorkingDirectoryIsNotGitRepoAndItsUnableToDeleteIt()
Project: gocd
File: GitMaterialTest.java
File: GitMaterialTest.java
@Test @RunIf(value = EnhancedOSChecker.class, arguments = { EnhancedOSChecker.WINDOWS }) public void shouldThrowExceptionWhenWorkingDirectoryIsNotGitRepoAndItsUnableToDeleteIt() throws Exception { File fileToBeLocked = new File(workingDir, "file"); RandomAccessFile lockedFile = new RandomAccessFile(fileToBeLocked, "rw"); FileLock lock = lockedFile.getChannel().lock(); try { git.latestModification(workingDir, new TestSubprocessExecutionContext()); fail("Should have failed to check modifications since the file is locked and cannot be removed."); } catch (Exception e) { assertEquals(e.getMessage().trim(), "Failed to delete directory: " + workingDir.getAbsolutePath().trim()); assertEquals(true, fileToBeLocked.exists()); } finally { lock.release(); } }
21. StoredInteger#setAndSync()
Project: concourse
File: StoredInteger.java
File: StoredInteger.java
/** * Atomically set the value equal to {@code value} and {@link #sync()} the * change to disk. * * @param value the new value */ public void setAndSync(int value) { FileLock lock = null; try { lock = channel.lock(position, 4, false); setUnsafe(value); sync(); } catch (IOException e) { throw Throwables.propagate(e); } finally { FileLocks.release(lock); } }
22. StoredInteger#set()
Project: concourse
File: StoredInteger.java
File: StoredInteger.java
/** * Set the value equal to {@code value} * * @param value the new value */ public void set(int value) { FileLock lock = null; try { lock = channel.lock(position, 4, false); setUnsafe(value); } catch (IOException e) { throw Throwables.propagate(e); } finally { FileLocks.release(lock); } }
23. StoredInteger#get()
Project: concourse
File: StoredInteger.java
File: StoredInteger.java
/** * Return the current value. * * @return the current value */ public int get() { FileLock lock = null; try { lock = channel.lock(position, 4, true); return getUnsafe(); } catch (IOException e) { throw Throwables.propagate(e); } finally { FileLocks.release(lock); } }
24. StoredInteger#addAndGet()
Project: concourse
File: StoredInteger.java
File: StoredInteger.java
/** * Add {@code amount} to the current value and return the sum. * * @param amount the number to add to the current value * @return the sum of the current value and the added {@code amount}, which * becomes the new value */ public int addAndGet(int amount) { FileLock lock = null; try { lock = channel.lock(position, SIZE, false); int value = getUnsafe(); value = value + amount; return setUnsafe(value); } catch (IOException e) { throw Throwables.propagate(e); } finally { FileLocks.release(lock); } }
25. SharedMemory#write()
Project: concourse
File: SharedMemory.java
File: SharedMemory.java
/** * Write {@code data} to the shared memory segment. * <p> * This method grabs an exclusive lock on the shared memory so that no other * readers or writers may access while the message is being written. As * such, this method also <strong>blocks</strong> while waiting for the * memory segment to become available for writing. * </p> * <p> * <strong>CAUTION:</strong> This method does not check to make sure that * the most recent message was read before writing. * </p> * * @param data the message to write to the memory segment * @return {@link SharedMemory this} */ public SharedMemory write(ByteBuffer data) { while (data.capacity() + 4 > memory.remaining()) { grow(); } FileLock lock = writeLock(); try { int position = nextWrite.get(); memory.position(position); int mark = memory.position(); memory.putInt(data.capacity()); memory.put(ByteBuffers.rewind(data)); nextWrite.setAndSync(memory.position()); // equal to the position of the message that was just written if (nextRead.get() < 0) { // fsync is necessary in case reader nextRead.setAndSync(mark); // is waiting on filesystem // notification } return this; } finally { FileLocks.release(lock); } }
26. SharedMemory#compact()
Project: concourse
File: SharedMemory.java
File: SharedMemory.java
/** * Run compact on the {@link SharedMemory} to occupy how much space is * utilized by removing garbage. */ public void compact() { FileLock lock = lock(); try { int position = nextRead.get(); int garbage = position; memory.position(position); memory.compact(); nextRead.addAndGet(-garbage); nextWrite.addAndGet(-garbage); nextWrite.sync(); nextRead.sync(); memory.force(); } finally { FileLocks.release(lock); } }
27. FileLockExclusiveReadLockStrategy#doReleaseExclusiveReadLock()
Project: camel
File: FileLockExclusiveReadLockStrategy.java
File: FileLockExclusiveReadLockStrategy.java
@Override protected void doReleaseExclusiveReadLock(GenericFileOperations<File> operations, GenericFile<File> file, Exchange exchange) throws Exception { // must call super super.doReleaseExclusiveReadLock(operations, file, exchange); FileLock lock = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_EXCLUSIVE_LOCK), FileLock.class); RandomAccessFile rac = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_EXCLUSIVE_LOCK), RandomAccessFile.class); String target = file.getFileName(); if (lock != null) { Channel channel = lock.acquiredBy(); try { lock.release(); } finally { // close channel as well IOHelper.close(channel, "while releasing exclusive read lock for file: " + target, LOG); IOHelper.close(rac, "while releasing exclusive read lock for file: " + target, LOG); } } }
28. TemporaryFileInstaller#install()
Project: asakusafw
File: TemporaryFileInstaller.java
File: TemporaryFileInstaller.java
/** * Installs contents into the target file. * @param target the target file * @param reuse {@code true} to reuse installed file, otherwise {@code false} * @return {@code true} if target file is successfully installed, * or {@code false} if the file is already installed * @throws IOException if error occurred while installing the target file */ public boolean install(File target, boolean reuse) throws IOException { File parent = target.getAbsoluteFile().getParentFile(); if (parent.mkdirs() == false && parent.isDirectory() == false) { throw new IOException(MessageFormat.format(//$NON-NLS-1$ Messages.getString("TemporaryFileInstaller.errorFailedToCreateFile"), target)); } try (//$NON-NLS-1$ RandomAccessFile file = new RandomAccessFile(target, "rw"); FileLock lock = file.getChannel().lock(0, 0, false)) { if (reuse && isReusable(target, file)) { //$NON-NLS-1$ LOG.debug("we reuse a temporary file: {}", target); return false; } //$NON-NLS-1$ LOG.debug("creating a temporary file: {}", target); doInstall(target, file); return true; } }
29. FileLockNodeManager#isBackupLive()
Project: activemq-artemis
File: FileLockNodeManager.java
File: FileLockNodeManager.java
@Override public boolean isBackupLive() throws Exception { FileLock liveAttemptLock; liveAttemptLock = tryLock(FileLockNodeManager.LIVE_LOCK_POS); if (liveAttemptLock == null) { return true; } else { liveAttemptLock.release(); return false; } }
30. AIOFileLockNodeManager#tryLock()
Project: activemq-artemis
File: AIOFileLockNodeManager.java
File: AIOFileLockNodeManager.java
@Override protected FileLock tryLock(final int lockPos) throws Exception { File file = newFileForRegionLock(lockPos); LibaioFile fileControl = LibaioContext.openControlFile(file.getAbsolutePath(), false); if (!fileControl.lock()) { fileControl.close(); return null; } FileLock lock = new ActiveMQFileLock(fileControl); return lock; }
31. OldFileChannelTest#testTryLockOverlapping()
Project: j2objc
File: OldFileChannelTest.java
File: OldFileChannelTest.java
public void testTryLockOverlapping() throws IOException { FileLock lockOne = readWriteFileChannel.tryLock(0, 10, false); FileLock lockTwo = readWriteFileChannel.tryLock(10, 20, false); assertLockFails(0, 10); lockOne.release(); assertLockFails(5, 10); lockOne = readWriteFileChannel.tryLock(0, 10, false); lockTwo.release(); lockOne.release(); }
32. OldFileChannelTest#testTryLockVeryLarge()
Project: j2objc
File: OldFileChannelTest.java
File: OldFileChannelTest.java
public void testTryLockVeryLarge() throws IOException { long tooBig = Integer.MAX_VALUE + 1L; FileLock lock = readWriteFileChannel.tryLock(tooBig, 1, false); assertLockFails(tooBig, 1); lock.release(); lock = readWriteFileChannel.tryLock(0, tooBig, false); assertLockFails(0, 1); lock.release(); }
33. FileSystemBinaryStoreTest#shouldKeepLockWhileMovingLockedFile()
Project: modeshape
File: FileSystemBinaryStoreTest.java
File: FileSystemBinaryStoreTest.java
@Test public void shouldKeepLockWhileMovingLockedFile() throws IOException { File tmpDir = new File("target"); System.out.println("Temporary directory for tests: " + tmpDir.getAbsolutePath()); assertThat(tmpDir.exists(), is(true)); assertThat(tmpDir.canRead(), is(true)); assertThat(tmpDir.canWrite(), is(true)); assertThat(tmpDir.isDirectory(), is(true)); File file1 = new File(tmpDir, "lockFile"); // file1.createNewFile(); // Lock the file ... RandomAccessFile raf = new RandomAccessFile(file1, "rw"); FileLock fileLock = raf.getChannel().lock(); // Now try moving our locked file ... File file2 = new File(tmpDir, "afterMove"); if (!file1.renameTo(file2)) { LOGGER.warn("RenameTo not successful. Will be ignored if on Windows"); if (System.getProperty("os.name").toLowerCase().contains("windows")) { fileLock.release(); return; } } fileLock.release(); assertThat(file1.exists(), is(false)); assertThat(file2.exists(), is(true)); }
34. FileLocksTest#testReadLocks()
Project: ignite
File: FileLocksTest.java
File: FileLocksTest.java
/** * @throws Exception If failed. */ public void testReadLocks() throws Exception { final File file = new File(LOCK_FILE_PATH); file.createNewFile(); RandomAccessFile raf = new RandomAccessFile(file, "r"); System.out.println("Getting lock..."); FileLock lock = raf.getChannel().lock(0, Long.MAX_VALUE, true); System.out.println("Obtained lock: " + lock); Thread thread = new Thread(new Runnable() { @Override public void run() { try { RandomAccessFile raf = new RandomAccessFile(file, "r"); System.out.println("Getting lock (parallel thread)..."); FileLock lock = raf.getChannel().lock(0, Long.MAX_VALUE, true); System.out.println("Obtained lock (parallel thread): " + lock); lock.release(); } catch (Throwable e) { e.printStackTrace(); } } }); thread.start(); JOptionPane.showMessageDialog(null, "Press OK to release lock."); lock.release(); thread.join(); }
35. FileLocksTest#testWriteLocks()
Project: ignite
File: FileLocksTest.java
File: FileLocksTest.java
/** * @throws Exception If failed. */ public void testWriteLocks() throws Exception { final File file = new File(LOCK_FILE_PATH); file.createNewFile(); RandomAccessFile raf = new RandomAccessFile(file, "rw"); System.out.println("Getting lock..."); FileLock lock = raf.getChannel().lock(); System.out.println("Obtained lock: " + lock); Thread thread = new Thread(new Runnable() { @Override public void run() { try { RandomAccessFile raf = new RandomAccessFile(file, "rw"); System.out.println("Getting lock (parallel thread)..."); FileLock lock = raf.getChannel().lock(); System.out.println("Obtained lock (parallel tread): " + lock); lock.release(); } catch (Throwable e) { e.printStackTrace(); } } }); thread.start(); JOptionPane.showMessageDialog(null, "Press OK to release lock."); lock.release(); thread.join(); }
36. Storage#isLockSupported()
Project: hadoop-hdfs
File: Storage.java
File: Storage.java
/** * Check whether underlying file system supports file locking. * * @return <code>true</code> if exclusive locks are supported or * <code>false</code> otherwise. * @throws IOException * @see StorageDirectory#lock() */ public boolean isLockSupported(int idx) throws IOException { StorageDirectory sd = storageDirs.get(idx); FileLock firstLock = null; FileLock secondLock = null; try { firstLock = sd.lock; if (firstLock == null) { firstLock = sd.tryLock(); if (firstLock == null) return true; } secondLock = sd.tryLock(); if (secondLock == null) return true; } finally { if (firstLock != null && firstLock != sd.lock) { firstLock.release(); firstLock.channel().close(); } if (secondLock != null) { secondLock.release(); secondLock.channel().close(); } } return false; }
37. Storage#isLockSupported()
Project: hadoop-common
File: Storage.java
File: Storage.java
/** * Check whether underlying file system supports file locking. * * @return <code>true</code> if exclusive locks are supported or * <code>false</code> otherwise. * @throws IOException * @see StorageDirectory#lock() */ public boolean isLockSupported(int idx) throws IOException { StorageDirectory sd = storageDirs.get(idx); FileLock firstLock = null; FileLock secondLock = null; try { firstLock = sd.lock; if (firstLock == null) { firstLock = sd.tryLock(); if (firstLock == null) return true; } secondLock = sd.tryLock(); if (secondLock == null) return true; } finally { if (firstLock != null && firstLock != sd.lock) { firstLock.release(); firstLock.channel().close(); } if (secondLock != null) { secondLock.release(); secondLock.channel().close(); } } return false; }
38. Storage#isLockSupported()
Project: hadoop-20
File: Storage.java
File: Storage.java
/** * Check whether underlying file system supports file locking. * * @return <code>true</code> if exclusive locks are supported or * <code>false</code> otherwise. * @throws IOException * @see StorageDirectory#lock() */ public boolean isLockSupported(int idx) throws IOException { StorageDirectory sd = storageDirs.get(idx); FileLock firstLock = null; FileLock secondLock = null; try { firstLock = sd.lock; if (firstLock == null) { firstLock = sd.tryLock(); if (firstLock == null) return true; } secondLock = sd.tryLock(); if (secondLock == null) return true; } finally { if (firstLock != null && firstLock != sd.lock) { firstLock.release(); firstLock.channel().close(); } if (secondLock != null) { secondLock.release(); secondLock.channel().close(); } } return false; }
39. TestFileSystem#testSimple()
Project: ThriftyPaxos
File: TestFileSystem.java
File: TestFileSystem.java
private void testSimple(final String fsBase) throws Exception { long time = System.currentTimeMillis(); for (String s : FileUtils.newDirectoryStream(fsBase)) { FileUtils.delete(s); } FileUtils.createDirectories(fsBase + "/test"); assertTrue(FileUtils.exists(fsBase)); FileUtils.delete(fsBase + "/test"); FileUtils.delete(fsBase + "/test2"); assertTrue(FileUtils.createFile(fsBase + "/test")); List<FilePath> p = FilePath.get(fsBase).newDirectoryStream(); assertEquals(1, p.size()); String can = FilePath.get(fsBase + "/test").toRealPath().toString(); assertEquals(can, p.get(0).toString()); assertTrue(FileUtils.canWrite(fsBase + "/test")); FileChannel channel = FileUtils.open(fsBase + "/test", "rw"); byte[] buffer = new byte[10000]; Random random = new Random(1); random.nextBytes(buffer); channel.write(ByteBuffer.wrap(buffer)); assertEquals(10000, channel.size()); channel.position(20000); assertEquals(20000, channel.position()); assertEquals(-1, channel.read(ByteBuffer.wrap(buffer, 0, 1))); String path = fsBase + "/test"; assertEquals("test", FileUtils.getName(path)); can = FilePath.get(fsBase).toRealPath().toString(); String can2 = FileUtils.toRealPath(FileUtils.getParent(path)); assertEquals(can, can2); FileLock lock = channel.tryLock(); if (lock != null) { lock.release(); } assertEquals(10000, channel.size()); channel.close(); assertEquals(10000, FileUtils.size(fsBase + "/test")); channel = FileUtils.open(fsBase + "/test", "r"); final byte[] test = new byte[10000]; FileUtils.readFully(channel, ByteBuffer.wrap(test, 0, 10000)); assertEquals(buffer, test); final FileChannel fc = channel; new AssertThrows(IOException.class) { @Override public void test() throws Exception { fc.write(ByteBuffer.wrap(test, 0, 10)); } }; new AssertThrows(NonWritableChannelException.class) { @Override public void test() throws Exception { fc.truncate(10); } }; channel.close(); long lastMod = FileUtils.lastModified(fsBase + "/test"); if (lastMod < time - 1999) { assertEquals(time, lastMod); } assertEquals(10000, FileUtils.size(fsBase + "/test")); List<String> list = FileUtils.newDirectoryStream(fsBase); assertEquals(1, list.size()); assertTrue(list.get(0).endsWith("test")); IOUtils.copyFiles(fsBase + "/test", fsBase + "/test3"); FileUtils.move(fsBase + "/test3", fsBase + "/test2"); FileUtils.move(fsBase + "/test2", fsBase + "/test2"); assertTrue(!FileUtils.exists(fsBase + "/test3")); assertTrue(FileUtils.exists(fsBase + "/test2")); assertEquals(10000, FileUtils.size(fsBase + "/test2")); byte[] buffer2 = new byte[10000]; InputStream in = FileUtils.newInputStream(fsBase + "/test2"); int pos = 0; while (true) { int l = in.read(buffer2, pos, Math.min(10000 - pos, 1000)); if (l <= 0) { break; } pos += l; } in.close(); assertEquals(10000, pos); assertEquals(buffer, buffer2); assertTrue(FileUtils.tryDelete(fsBase + "/test2")); FileUtils.delete(fsBase + "/test"); if (fsBase.indexOf("memFS:") < 0 && fsBase.indexOf("memLZF:") < 0 && fsBase.indexOf("nioMemFS:") < 0 && fsBase.indexOf("nioMemLZF:") < 0) { FileUtils.createDirectories(fsBase + "/testDir"); assertTrue(FileUtils.isDirectory(fsBase + "/testDir")); if (!fsBase.startsWith("jdbc:")) { FileUtils.deleteRecursive(fsBase + "/testDir", false); assertTrue(!FileUtils.exists(fsBase + "/testDir")); } } }
40. FilePathRetryOnInterrupt#tryLock()
Project: ThriftyPaxos
File: FilePathRetryOnInterrupt.java
File: FilePathRetryOnInterrupt.java
@Override public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException { FileLock l = channel.tryLock(position, size, shared); if (l == null) { return null; } lock = new FileLockRetry(l, this); return lock; }
41. FilePathNioMem#tryLock()
Project: ThriftyPaxos
File: FilePathNioMem.java
File: FilePathNioMem.java
@Override public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException { if (shared) { if (!data.lockShared()) { return null; } } else { if (!data.lockExclusive()) { return null; } } FileLock lock = new FileLock((FileChannel) null, position, size, shared) { @Override public boolean isValid() { return true; } @Override public void release() throws IOException { data.unlock(); } }; return lock; }
42. FilePathMem#tryLock()
Project: ThriftyPaxos
File: FilePathMem.java
File: FilePathMem.java
@Override public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException { if (shared) { if (!data.lockShared()) { return null; } } else { if (!data.lockExclusive()) { return null; } } FileLock lock = new FileLock((FileChannel) null, position, size, shared) { @Override public boolean isValid() { return true; } @Override public void release() throws IOException { data.unlock(); } }; return lock; }
43. Fetcher#doSharedFetch()
Project: tez
File: Fetcher.java
File: Fetcher.java
protected HostFetchResult doSharedFetch() throws IOException { int inputs = findInputs(); if (inputs == srcAttemptsRemaining.size()) { if (isDebugEnabled) { LOG.debug("Using the copies found locally"); } return doLocalDiskFetch(true); } if (inputs > 0) { if (isDebugEnabled) { LOG.debug("Found " + input + " local fetches right now, using them first"); } return doLocalDiskFetch(false); } FileLock lock = null; try { lock = getLock(); if (lock == null) { // re-queue until we get a lock return new HostFetchResult(new FetchResult(host, port, partition, srcAttemptsRemaining.values(), "Requeuing as we didn't get a lock"), null, false); } else { if (findInputs() == srcAttemptsRemaining.size()) { // double checked after lock releaseLock(lock); lock = null; return doLocalDiskFetch(true); } // cache data if possible return doHttpFetch(new CachingCallBack()); } } catch (OverlappingFileLockException jvmCrossLock) { LOG.warn("Double locking detected for " + host); } catch (InterruptedException sleepInterrupted) { Thread.currentThread().interrupt(); LOG.warn("Lock was interrupted for " + host); } finally { releaseLock(lock); } if (isShutDown.get()) { // requests return new HostFetchResult(new FetchResult(host, port, partition, srcAttemptsRemaining.values()), null, false); } // no more caching return doHttpFetch(); }
44. AdvisoryFileLock#create()
Project: team-explorer-everywhere
File: AdvisoryFileLock.java
File: AdvisoryFileLock.java
/** * Creates an {@link AdvisoryFileLock} that mediates access to the given * file path. Blocks forever (or until thread interrupted) if block is true, * returns immediately if block if false. * * @param lockFile * the file to lock (not null). This file does not have to exist, but * it will be created (0 bytes) if it does not * @param block * if true, this method does not return until the lock is obtained * (or the controlling thread is interrupted). If false, the method * returns immediately; the value is null if the lock was not * immediately available or an {@link AdvisoryFileLock} if it was. * @return an {@link AdvisoryFileLock}, initially owned. Returns null if and * only if block was set to false and the lock was not immediately * available. * @throws IOException * if an error occurred accessing the given lock file path on disk. * @throws InterruptedException * if this thread was interrupted while waiting for its turn to * become the only thread in this VM to lock the given file path. */ public static AdvisoryFileLock create(final File lockFile, final boolean block) throws IOException, InterruptedException { //$NON-NLS-1$ Check.notNull(lockFile, "lockFile"); /* * The random access file gives us filesystem locking (manditory on some * platforms, advisory on others). */ //$NON-NLS-1$ final RandomAccessFile raf = new RandomAccessFile(lockFile, "rw"); /* * This is the lock object we wish to acquire (initially held). */ FileLock lock; synchronized (AdvisoryFileLock.heldLocks) { if (block) { /* * If the set already contains this path, wait until it is * removed. The set is notified upon removal of a path so our * wait will complete. */ while (AdvisoryFileLock.heldLocks.contains(lockFile)) { AdvisoryFileLock.heldLocks.wait(); } /* * We now have the lock on the set of paths, and our path is not * in that set. It is safe to lock the path we were given * through its FileChannel. * * WARNING: Javadoc for FileChannel.lock() says it will block * until the lock is available, or throw if some lockable * condition happens. Turns out this method may return null if * it can't lock, instead of throwing. See this (still open in * January 2010) Sun bug link: * * http://bugs.sun.com/view_bug.do?bug_id=6209658 * * I can't tell if Sun plans to ever fix this, so we'll assume * that all null locks in the blocking path mean the current * thread was interrupted. */ lock = raf.getChannel().lock(); if (lock == null) { raf.close(); //$NON-NLS-1$ final String messageFormat = Messages.getString("AdvisoryFileLock.InterruptedAcquiringLockFormat"); final String message = MessageFormat.format(messageFormat, lockFile); throw new InterruptedException(message); } } else { /* * If the set already contains this path, we will fail fast. */ if (AdvisoryFileLock.heldLocks.contains(lockFile)) { return null; } lock = raf.getChannel().tryLock(); if (lock == null) { raf.close(); return null; } } /* * Our lock is held, add it to the set. */ AdvisoryFileLock.heldLocks.add(lockFile); } return new AdvisoryFileLock(lockFile, lock, raf); }
45. CoreUtil#execCore()
Project: OSMonitor
File: CoreUtil.java
File: CoreUtil.java
/** * execute osmcore as a binary execute * * @param context * @throws InterruptedException */ public static boolean execCore(Context context) { boolean flag = false; if (context == null) return flag; String binary = CoreUtil.getBinaryName(context); String socket = CoreUtil.getSocketName(context); String uid = CoreUtil.getUid(context); final Settings settings = Settings.getInstance(context); restoreSecurityContext(binary, settings); // copy file if (!copyFile("osmcore", binary, context)) return flag; // write token file if (!writeTokenFile(binary + ".token", settings.getToken())) return flag; // lock file File file = new File(binary + ".lock"); FileChannel channel = null; FileLock lock = null; try { channel = new RandomAccessFile(file, "rw").getChannel(); lock = channel.tryLock(); } catch (Exception e) { return flag; } // execute osmcore try { CoreUtil.runSHELL(new String[] { "chmod", "755", binary }); if (!settings.isRoot()) { CoreUtil.runSHELL(new String[] { binary, binary + ".token", socket, uid, "&" }); } else { if (!CoreUtil.isGreaterThanLollipop()) { CoreUtil.runSU(new String[] { binary, binary + ".token", socket, uid, "&" }); } else { boolean supportSecurityContext = CoreUtil.isSupportSecurityContext(); CoreUtil.runSU(new String[] { "chcon", "u:object_r:system_file:s0", binary }); if (!supportSecurityContext) CoreUtil.runSU(new String[] { "su", "-c", "\"" + binary, binary + ".token", socket, uid, " &\" &" }); else CoreUtil.runSU(new String[] { "su", "--context", "u:r:init:s0", "-c", "\"" + binary, binary + ".token", socket, uid, " &\" &" }); if (CoreUtil.isGreaterThanMarshmallow()) { CoreUtil.runSU(new String[] { "restorecon", binary }); CoreUtil.runSU(new String[] { "restorecon", socket }); } else CoreUtil.runSU(new String[] { "chcon", "u:object_r:app_data_file:s0", binary }); } } flag = true; } catch (Exception e) { } // release the lock try { lock.release(); channel.close(); } catch (Exception e) { } return flag; }
46. FileLockConstructor#main()
Project: openjdk
File: FileLockConstructor.java
File: FileLockConstructor.java
public static void main(String[] args) throws IOException { FileLock fileLock = null; int failures = 0; // null FileChannel boolean exceptionThrown = false; try { fileLock = new FileLockSub((FileChannel) null, 0, 0, false); } catch (NullPointerException npe) { exceptionThrown = true; } if (!exceptionThrown) { System.err.println("FileLock constructor did not throw NPE for null FileChannel"); failures++; } // null AsynchronousFileChannel exceptionThrown = false; try { fileLock = new FileLockSub((AsynchronousFileChannel) null, 0, 0, true); } catch (NullPointerException npe) { exceptionThrown = true; } if (!exceptionThrown) { System.err.println("FileLock constructor did not throw NPE for null AsynchronousFileChannel"); failures++; } // create temporary file File tmpFile = File.createTempFile("FileLock", "tmp"); tmpFile.deleteOnExit(); // position and size preconditions long[][] posAndSize = new long[][] { // valid { 0, 42 }, // invalid: position < 0 { -1, 42 }, // invalid: size < 0 { 0, -1 }, // invalid: position + size < 0 { Long.MAX_VALUE, 1 } }; // test position and size preconditions for FileChannel case try (FileChannel syncChannel = FileChannel.open(tmpFile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE)) { for (int i = 0; i < posAndSize.length; i++) { boolean preconditionsHold = i == 0; exceptionThrown = false; try { fileLock = new FileLockSub(syncChannel, posAndSize[i][0], posAndSize[i][1], true); } catch (IllegalArgumentException iae) { exceptionThrown = true; } catch (Exception e) { System.err.println("Unexpected exception \"" + e + "\" caught" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for FileChannel variant"); failures++; continue; } if (preconditionsHold && exceptionThrown) { System.err.println("FileLock constructor incorrectly threw IAE" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for FileChannel variant"); failures++; } else if (!preconditionsHold && !exceptionThrown) { System.err.println("FileLock constructor did not throw IAE" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for FileChannel variant"); failures++; } } } // test position and size preconditions for AsynchronousFileChannel case try (AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(tmpFile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE)) { for (int i = 0; i < posAndSize.length; i++) { boolean preconditionsHold = i == 0; exceptionThrown = false; try { fileLock = new FileLockSub(asyncChannel, posAndSize[i][0], posAndSize[i][1], true); } catch (IllegalArgumentException iae) { exceptionThrown = true; } catch (Exception e) { System.err.println("Unexpected exception \"" + e + "\" caught" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for AsynchronousFileChannel variant"); failures++; continue; } if (preconditionsHold && exceptionThrown) { System.err.println("FileLock constructor incorrectly threw IAE" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for AsynchronousFileChannel variant"); failures++; } else if (!preconditionsHold && !exceptionThrown) { System.err.println("FileLock constructor did not throw IAE" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for AsynchronousFileChannel variant"); failures++; } } } if (failures > 0) { throw new RuntimeException("Incurred " + failures + " failures while testing FileLock."); } }
47. Sharing#TestMultipleFD()
Project: openjdk
File: Sharing.java
File: Sharing.java
/** * Exercise FileDispatcher close()/preClose() */ private static void TestMultipleFD() throws Exception { RandomAccessFile raf = null; FileOutputStream fos = null; FileInputStream fis = null; FileChannel fc = null; FileLock fileLock = null; File test1 = new File("test1"); try { raf = new RandomAccessFile(test1, "rw"); fos = new FileOutputStream(raf.getFD()); fis = new FileInputStream(raf.getFD()); fc = raf.getChannel(); fileLock = fc.lock(); raf.setLength(0L); fos.flush(); fos.write("TEST".getBytes()); } finally { if (fileLock != null) fileLock.release(); if (fis != null) fis.close(); if (fos != null) fos.close(); if (raf != null) raf.close(); test1.delete(); } /* * Close out in different order to ensure FD is not * closed out too early */ File test2 = new File("test2"); try { raf = new RandomAccessFile(test2, "rw"); fos = new FileOutputStream(raf.getFD()); fis = new FileInputStream(raf.getFD()); fc = raf.getChannel(); fileLock = fc.lock(); raf.setLength(0L); fos.flush(); fos.write("TEST".getBytes()); } finally { if (fileLock != null) fileLock.release(); if (raf != null) raf.close(); if (fos != null) fos.close(); if (fis != null) fis.close(); test2.delete(); } // one more time, fos first this time File test3 = new File("test3"); try { raf = new RandomAccessFile(test3, "rw"); fos = new FileOutputStream(raf.getFD()); fis = new FileInputStream(raf.getFD()); fc = raf.getChannel(); fileLock = fc.lock(); raf.setLength(0L); fos.flush(); fos.write("TEST".getBytes()); } finally { if (fileLock != null) fileLock.release(); if (fos != null) fos.close(); if (raf != null) raf.close(); if (fis != null) fis.close(); test3.delete(); } }
48. Main#startServer()
Project: onos
File: Main.java
File: Main.java
// Initiates a server. private static void startServer(String[] args) throws IOException, CheckstyleException { String portLock = args[0]; String buckPid = args[1]; String checkstyleFile = args[2]; String suppressionsFile = args[3]; // Use a file lock to ensure only one copy of the daemon runs Path portLockPath = Paths.get(portLock); FileChannel channel = FileChannel.open(portLockPath, WRITE, CREATE); FileLock lock = channel.tryLock(); if (lock == null) { System.out.println("Server is already running"); System.exit(1); } //else, hold the lock until the JVM exits // Start the server and bind it to a random port ServerSocket server = new ServerSocket(0); // Monitor the parent buck process watchProcess(buckPid); // Set up hook to clean up after ourselves Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { if (channel != null) { channel.truncate(0); channel.close(); } System.err.println("tear down..."); Files.delete(portLockPath); } catch (IOException e) { e.printStackTrace(); } })); // Write the bound port to the port file int port = server.getLocalPort(); channel.truncate(0); channel.write(ByteBuffer.wrap(Integer.toString(port).getBytes())); // Instantiate a Checkstyle runner and executor; serve until exit... CheckstyleRunner runner = new CheckstyleRunner(checkstyleFile, suppressionsFile); ExecutorService executor = Executors.newCachedThreadPool(); while (true) { try { executor.submit(runner.checkClass(server.accept())); } catch (Exception e) { e.printStackTrace(); } } }
49. CleanMojoTest#testCleanLockedFileWithNoError()
Project: maven-plugins
File: CleanMojoTest.java
File: CleanMojoTest.java
/** * Test the removal of a locked file on Windows systems. * <br/> * Note: Unix systems doesn't lock any files. * * @throws Exception */ public void testCleanLockedFileWithNoError() throws Exception { if (!System.getProperty("os.name").toLowerCase().contains("windows")) { assertTrue("Ignored this test on none Windows based systems", true); return; } String pluginPom = getBasedir() + "/src/test/resources/unit/locked-file-test/plugin-pom.xml"; // safety FileUtils.copyDirectory(new File(getBasedir(), "src/test/resources/unit/locked-file-test"), new File(getBasedir(), "target/test-classes/unit/locked-file-test"), null, "**/.svn,**/.svn/**"); CleanMojo mojo = (CleanMojo) lookupMojo("clean", pluginPom); setVariableValueToObject(mojo, "failOnError", Boolean.FALSE); assertNotNull(mojo); File f = new File(getBasedir(), "target/test-classes/unit/locked-file-test/buildDirectory/file.txt"); FileChannel channel = null; FileLock lock = null; try { channel = new RandomAccessFile(f, "rw").getChannel(); lock = channel.lock(); mojo.execute(); assertTrue(true); } catch (MojoExecutionException expected) { fail("Should display a warning when deleting a file that is locked"); } finally { if (lock != null) { lock.release(); } if (channel != null) { channel.close(); } } }
50. CleanMojoTest#testCleanLockedFile()
Project: maven-plugins
File: CleanMojoTest.java
File: CleanMojoTest.java
/** * Test the removal of a locked file on Windows systems. * <br/> * Note: Unix systems doesn't lock any files. * * @throws Exception */ public void testCleanLockedFile() throws Exception { if (!System.getProperty("os.name").toLowerCase().contains("windows")) { assertTrue("Ignored this test on none Windows based systems", true); return; } String pluginPom = getBasedir() + "/src/test/resources/unit/locked-file-test/plugin-pom.xml"; // safety FileUtils.copyDirectory(new File(getBasedir(), "src/test/resources/unit/locked-file-test"), new File(getBasedir(), "target/test-classes/unit/locked-file-test"), null, "**/.svn,**/.svn/**"); CleanMojo mojo = (CleanMojo) lookupMojo("clean", pluginPom); assertNotNull(mojo); File f = new File(getBasedir(), "target/test-classes/unit/locked-file-test/buildDirectory/file.txt"); FileChannel channel = null; FileLock lock = null; try { channel = new RandomAccessFile(f, "rw").getChannel(); lock = channel.lock(); mojo.execute(); fail("Should fail to delete a file that is locked"); } catch (MojoExecutionException expected) { assertTrue(true); } finally { if (lock != null) { lock.release(); } if (channel != null) { channel.close(); } } }
51. Sharing#TestMultipleFD()
Project: jdk7u-jdk
File: Sharing.java
File: Sharing.java
/** * Exercise FileDispatcher close()/preClose() */ private static void TestMultipleFD() throws Exception { RandomAccessFile raf = null; FileOutputStream fos = null; FileInputStream fis = null; FileChannel fc = null; FileLock fileLock = null; File test1 = new File("test1"); try { raf = new RandomAccessFile(test1, "rw"); fos = new FileOutputStream(raf.getFD()); fis = new FileInputStream(raf.getFD()); fc = raf.getChannel(); fileLock = fc.lock(); raf.setLength(0L); fos.flush(); fos.write("TEST".getBytes()); } finally { if (fileLock != null) fileLock.release(); if (fis != null) fis.close(); if (fos != null) fos.close(); if (raf != null) raf.close(); test1.delete(); } /* * Close out in different order to ensure FD is not * closed out too early */ File test2 = new File("test2"); try { raf = new RandomAccessFile(test2, "rw"); fos = new FileOutputStream(raf.getFD()); fis = new FileInputStream(raf.getFD()); fc = raf.getChannel(); fileLock = fc.lock(); raf.setLength(0L); fos.flush(); fos.write("TEST".getBytes()); } finally { if (fileLock != null) fileLock.release(); if (raf != null) raf.close(); if (fos != null) fos.close(); if (fis != null) fis.close(); test2.delete(); } // one more time, fos first this time File test3 = new File("test3"); try { raf = new RandomAccessFile(test3, "rw"); fos = new FileOutputStream(raf.getFD()); fis = new FileInputStream(raf.getFD()); fc = raf.getChannel(); fileLock = fc.lock(); raf.setLength(0L); fos.flush(); fos.write("TEST".getBytes()); } finally { if (fileLock != null) fileLock.release(); if (fos != null) fos.close(); if (raf != null) raf.close(); if (fis != null) fis.close(); test3.delete(); } }
52. FileChannelImpl#basicLock()
Project: j2objc
File: FileChannelImpl.java
File: FileChannelImpl.java
private FileLock basicLock(long position, long size, boolean shared, boolean wait) throws IOException { int accessMode = (mode & O_ACCMODE); if (accessMode == O_RDONLY) { if (!shared) { throw new NonWritableChannelException(); } } else if (accessMode == O_WRONLY) { if (shared) { throw new NonReadableChannelException(); } } if (position < 0 || size < 0) { throw new IllegalArgumentException("position=" + position + " size=" + size); } FileLock pendingLock = new FileLockImpl(this, position, size, shared); addLock(pendingLock); StructFlock flock = new StructFlock(); flock.l_type = (short) (shared ? F_RDLCK : F_WRLCK); flock.l_whence = (short) SEEK_SET; flock.l_start = position; flock.l_len = translateLockLength(size); boolean success = false; try { success = (Libcore.os.fcntlFlock(fd, wait ? F_SETLKW64 : F_SETLK64, flock) != -1); } catch (ErrnoException errnoException) { throw errnoException.rethrowAsIOException(); } finally { if (!success) { removeLock(pendingLock); } } return success ? pendingLock : null; }
53. Segment#isLocked()
Project: indextank-engine
File: Segment.java
File: Segment.java
public boolean isLocked() throws IOException { RandomAccessFile raf = new RandomAccessFile(buildFile(false), "rw"); FileLock lock = raf.getChannel().tryLock(); if (lock == null) return true; raf.close(); return false; }
54. HTracedSpanReceiver#appendToDroppedSpansLog()
Project: incubator-htrace
File: HTracedSpanReceiver.java
File: HTracedSpanReceiver.java
void appendToDroppedSpansLog(String text) throws IOException { // Is the dropped spans log is disabled? if (conf.droppedSpansLogPath.isEmpty() || (conf.droppedSpansLogMaxSize == 0)) { return; } FileLock lock = null; String msg = ISO_DATE_FORMAT.format(new Date()) + ": " + text; ByteBuffer bb = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)); // multiple HTracedSpanReceiver objects, but possible.) synchronized (HTracedSpanReceiver.class) { FileChannel channel = FileChannel.open(Paths.get(conf.droppedSpansLogPath), APPEND, CREATE, WRITE); try { lock = channel.lock(); long size = channel.size(); if (size > conf.droppedSpansLogMaxSize) { throw new IOException("Dropped spans log " + conf.droppedSpansLogPath + " is already " + size + " bytes; will not add to it."); } else if ((size == 0) && (DROPPED_SPANS_FILE_PERMS != null)) { // Set the permissions of the dropped spans file so that other // processes can write to it. Files.setPosixFilePermissions(Paths.get(conf.droppedSpansLogPath), DROPPED_SPANS_FILE_PERMS); } channel.write(bb); } finally { try { if (lock != null) { lock.release(); } } finally { channel.close(); } } } }
55. GridJmxPortFinder#main()
Project: ignite
File: GridJmxPortFinder.java
File: GridJmxPortFinder.java
/** * Makes a search of available port. Start port is taken from temp file, it is * then replaced with newly found port. * * @param args Program arguments. */ public static void main(String[] args) { try { InetAddress.getLocalHost(); } catch (UnknownHostException ignored) { return; } int jmxPort = IgniteSystemProperties.getInteger(IGNITE_JMX_PORT, -1); if (jmxPort != -1) { System.out.println(jmxPort); return; } RandomAccessFile ra = null; FileLock lock = null; try { File file = new File(System.getProperty("java.io.tmpdir"), "ignite.lastport.tmp"); file.setReadable(true, false); file.setWritable(true, false); ra = new RandomAccessFile(file, "rw"); lock = ra.getChannel().lock(); ra.seek(0); String startPortStr = ra.readLine(); int startPort = MIN_PORT; if (startPortStr != null && !startPortStr.isEmpty()) { try { startPort = Integer.valueOf(startPortStr) + 1; if (startPort < MIN_PORT || startPort > MAX_PORT) startPort = MIN_PORT; } catch (NumberFormatException ignored) { } } int port = findPort(startPort); ra.setLength(0); ra.writeBytes(String.valueOf(port)); // Ack the port for others to read... System.out.println(port); } catch (IOException ignored) { } finally { if (lock != null) try { lock.release(); } catch (IOException ignored) { } if (ra != null) try { ra.close(); } catch (IOException ignored) { } } }
56. IpcSharedMemoryNativeLoader#doLoad()
Project: ignite
File: IpcSharedMemoryNativeLoader.java
File: IpcSharedMemoryNativeLoader.java
/** * @throws IgniteCheckedException If failed. */ private static void doLoad(IgniteLogger log) throws IgniteCheckedException { assert Thread.holdsLock(IpcSharedMemoryNativeLoader.class); Collection<Throwable> errs = new ArrayList<>(); try { // Load native library (the library directory should be in java.library.path). System.loadLibrary(LIB_NAME); return; } catch (UnsatisfiedLinkError e) { errs.add(e); } File tmpDir = getUserSpecificTempDir(); File lockFile = new File(tmpDir, "igniteshmem.lock"); // Obtain lock on file to prevent concurrent extracts. try (RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile, "rws"); FileLock ignored = randomAccessFile.getChannel().lock()) { if (extractAndLoad(errs, tmpDir, platformSpecificResourcePath())) return; if (extractAndLoad(errs, tmpDir, osSpecificResourcePath())) return; if (extractAndLoad(errs, tmpDir, resourcePath())) return; try { if (log != null) LT.warn(log, null, "Failed to load 'igniteshmem' library from classpath. Will try to load it from IGNITE_HOME."); String igniteHome = X.resolveIgniteHome(); File shmemJar = findShmemJar(errs, igniteHome); if (shmemJar != null) { try (JarFile jar = new JarFile(shmemJar, false, JarFile.OPEN_READ)) { if (extractAndLoad(errs, jar, tmpDir, platformSpecificResourcePath())) return; if (extractAndLoad(errs, jar, tmpDir, osSpecificResourcePath())) return; if (extractAndLoad(errs, jar, tmpDir, resourcePath())) return; } } } catch (IgniteCheckedException ignore) { } // Failed to find the library. assert !errs.isEmpty(); throw new IgniteCheckedException("Failed to load native IPC library: " + errs); } catch (IOException e) { throw new IgniteCheckedException("Failed to obtain file lock: " + lockFile, e); } }
57. JobPrefixFile#tryFromExistingFile()
Project: helios
File: JobPrefixFile.java
File: JobPrefixFile.java
/** * Attempts to lock the given file, and create a JobPrefixFile for it. A new JobPrefixFile * instance will be returned if a lock can be obtained for the file. Null will be returned if the * lock is already held by either this process or another. For all other cases, an exception will * be thrown. * @param file the path to the file * @return a new JobPrefixFile if a file lock can be obtained. Null if a lock for the file is * already held by either this process or another. */ public static JobPrefixFile tryFromExistingFile(final Path file) throws IOException { Preconditions.checkNotNull(file); final FileChannel channel = FileChannel.open(file, WRITE); final FileLock lock; try { // We want to return JobPrefixFile if we can obtain the lock, null if someone already holds // the lock, and throw an exception in all other cases. tryLock makes this a little tricky. // It's behavior this: // - returns a FileLock if one can be obtained // - returns null if another process holds the lock // - throws OverlappingFileLockException if the lock is already held by this process // - throws a various exceptions for other errors lock = channel.tryLock(); } catch (OverlappingFileLockException e) { close(channel); return null; } catch (Exception e) { close(channel); throw e; } // If another process hold the lock, close the channel and return null. if (lock == null) { close(channel); return null; } // If we've obtained the lock, return a new JobPrefixFile return new JobPrefixFile(file, channel, lock); }
58. CachingAvatarZooKeeperClient#tryLock()
Project: hadoop-20
File: CachingAvatarZooKeeperClient.java
File: CachingAvatarZooKeeperClient.java
private FileWithLock tryLock(ZooKeeperCall call) throws IOException, InterruptedException { File lockFile = call.getLockFile(cacheDir); RandomAccessFile file = null; for (int i = 0; i < 10; i++) { try { file = new RandomAccessFile(lockFile, "rws"); break; } catch (FileNotFoundException fnfe) { if (!new File(cacheDir).exists()) { new File(cacheDir).mkdir(); } if (i == 9) { throw fnfe; } else { Thread.sleep(250); } } } setRWPermissions(lockFile); FileLock lock = null; do { try { lock = file.getChannel().tryLock(); } catch (OverlappingFileLockException ex) { lock = null; Thread.sleep(1000); } } while (lock == null); return new FileWithLock(lock, file); }
59. GoFileConfigDataSource#writeToConfigXmlFile()
Project: gocd
File: GoFileConfigDataSource.java
File: GoFileConfigDataSource.java
private void writeToConfigXmlFile(String content) { FileChannel channel = null; FileOutputStream outputStream = null; FileLock lock = null; try { RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw"); channel = randomAccessFile.getChannel(); lock = channel.lock(); randomAccessFile.seek(0); randomAccessFile.setLength(0); outputStream = new FileOutputStream(randomAccessFile.getFD()); IOUtils.write(content, outputStream, UTF_8); } catch (Exception e) { throw new RuntimeException(e); } finally { if (channel != null && lock != null) { try { lock.release(); channel.close(); IOUtils.closeQuietly(outputStream); } catch (IOException e) { LOGGER.error("Error occured when releasing file lock and closing file.", e); } } } }
60. MFileManager#writeToFile()
Project: freeplane
File: MFileManager.java
File: MFileManager.java
/**@deprecated -- use MMapIO*/ @Deprecated public void writeToFile(final MapModel map, final File file) throws FileNotFoundException, IOException { final FileOutputStream out = new FileOutputStream(file); FileLock lock = null; try { boolean lockedByOtherApplication = false; try { lock = out.getChannel().tryLock(); lockedByOtherApplication = lock == null; } catch (Exception e) { LogUtils.warn(e.getMessage()); } if (lockedByOtherApplication) { throw new IOException("can not obtain file lock for " + file); } final BufferedWriter fileout = new BufferedWriter(new OutputStreamWriter(out)); Controller.getCurrentModeController().getMapController().getMapWriter().writeMapAsXml(map, fileout, Mode.FILE, true, false); } finally { if (lock != null && lock.isValid()) lock.release(); if (out != null) out.close(); } }
61. LockManager#writeSemaphoreFile()
Project: freeplane
File: LockManager.java
File: LockManager.java
private void writeSemaphoreFile(final File inSemaphoreFile) throws Exception { FileOutputStream semaphoreOutputStream; try { semaphoreOutputStream = new FileOutputStream(inSemaphoreFile); } catch (final FileNotFoundException e) { if (lockTimer != null) { lockTimer.cancel(); } return; } FileLock lock = null; try { lock = semaphoreOutputStream.getChannel().tryLock(); if (lock == null) { semaphoreOutputStream.close(); LogUtils.severe("Locking failed."); throw new Exception(); } } catch (final UnsatisfiedLinkError eUle) { } catch (final NoClassDefFoundError eDcdf) { } semaphoreOutputStream.write(System.getProperty("user.name").getBytes()); semaphoreOutputStream.write('\n'); semaphoreOutputStream.write(String.valueOf(System.currentTimeMillis()).getBytes()); FileUtils.setHidden(inSemaphoreFile, /* synchro= */ true, false); if (lock != null) { lock.release(); } semaphoreOutputStream.close(); semaphoreOutputStream = null; }
62. OsUtil#transferFileAtom()
Project: disconf
File: OsUtil.java
File: OsUtil.java
/** * @param src * @param dest * * @return void * * @Description: ??????? ATOM ???? ???????????? ??? * @author liaoqiqi * @date 2013-6-20 */ public static void transferFileAtom(File src, File dest, boolean isDeleteSource) throws Exception { // ??????? File lockFile = new File(dest + ".lock"); FileOutputStream outStream = null; FileLock lock = null; try { int tryTime = 0; while (tryTime < 3) { try { outStream = new FileOutputStream(lockFile); FileChannel channel = outStream.getChannel(); lock = channel.tryLock(); if (lock != null) { if (dest.exists()) { // ???????? if (FileUtils.isFileEqual(src, dest)) { // ??????????????????? if (isDeleteSource) { src.delete(); } break; } } logger.debug("start to replace " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()); // ?? transferFile(src, dest); // ????? if (isDeleteSource) { src.delete(); } break; } } catch (FileNotFoundException e) { logger.warn(e.toString()); } finally { // ???????????? if (null != lock) { try { lock.release(); } catch (IOException e) { logger.warn(e.toString()); } if (lockFile != null) { lockFile.delete(); } } if (outStream != null) { try { outStream.close(); } catch (IOException e) { logger.warn(e.toString()); } } } // ???? logger.warn("try lock failed. sleep and try " + tryTime); tryTime++; try { Thread.sleep(1000 * tryTime); } catch (Exception e) { System.out.print(""); } } } catch (IOException e) { logger.warn(e.toString()); } }
63. DefaultDirectoryService#lockWorkDir()
Project: directory-server
File: DefaultDirectoryService.java
File: DefaultDirectoryService.java
/** * checks if the working directory is already in use by some other directory service, if yes * then throws a runtime exception else will obtain the lock on the working directory */ private void lockWorkDir() { FileLock fileLock = null; try { lockFile = new RandomAccessFile(new File(instanceLayout.getInstanceDirectory(), LOCK_FILE_NAME), "rw"); try { fileLock = lockFile.getChannel().tryLock(0, 1, false); } catch (IOException e) { LOG.error("failed to lock the work directory", e); } catch (// thrown if we can't get a lock OverlappingFileLockException // thrown if we can't get a lock e) { fileLock = null; } } catch (FileNotFoundException e) { LOG.error("failed to lock the work directory", e); } if ((fileLock == null) || (!fileLock.isValid())) { String message = "the working directory " + instanceLayout.getRunDirectory() + " has been locked by another directory service."; LOG.error(message); throw new RuntimeException(message); } }
64. SharedMemory#grow()
Project: concourse
File: SharedMemory.java
File: SharedMemory.java
/** * Increase the capacity of the {@link #memory} segment. */ private void grow() { FileLock lock = lock(); try { growUnsafe(); } finally { FileLocks.release(lock); } }
65. SharedMemory#read()
Project: concourse
File: SharedMemory.java
File: SharedMemory.java
/** * Read the most recent message from the memory segment, blocking until a * message is available. * * @return a {@link ByteBuffer} that contains the most recent message */ public ByteBuffer read() { long start = System.currentTimeMillis(); if (preferBusyWait()) { for (int i = 0; i < MAX_SPIN_ROUNDS; ++i) { int spins = 0; while (nextRead.get() < 0 && spins < MAX_SPIN_CYCLES_PER_ROUND) { spins++; continue; } if (spins < MAX_SPIN_CYCLES_PER_ROUND) { break; } else { try { Thread.sleep(SPIN_BACKOFF_IN_MILLIS); } catch (InterruptedException e) { throw Throwables.propagate(e); } } } } while (nextRead.get() < 0) { FileOps.awaitChange(location); } FileLock lock = null; try { lock = readLock(); int position = nextRead.get(); if (position >= 0) { long elapsed = System.currentTimeMillis() - start; totalLatency += elapsed; memory.position(position); int length = memory.getInt(); ByteBuffer data = read(length); int mark = memory.position(); int next = -1; try { // Peek at the next 4 bytes to see if it is > 0, which // indicates that there is a next message to read. int peek = memory.getInt(); if (peek > 0) { next = mark; } } catch (BufferUnderflowException e) { } memory.position(mark); nextRead.setAndSync(next); return data; } else { // did. return read(); } } finally { FileLocks.release(lock); } }
66. IndexInfo#doWithFileLock()
Project: community-edition
File: IndexInfo.java
File: IndexInfo.java
/** * An iterative method that retries the operation in the event of the channel being closed. * * @param retriesRemaining * the number of retries remaining * @return Returns the lock work result */ private <R> R doWithFileLock(LockWork<R> lockWork, int retriesRemaining) throws Throwable { FileLock fileLock = null; R result = null; long start = 0L; try { // Check that the channel is open if (!indexInfoChannel.isOpen()) { if (lockWork.canRetry()) { throw new IndexInfoChannelException("Channel is closed. Manually triggering reopen attempts"); } else { reopenChannels(); } } if (indexIsShared) { if (s_logger.isDebugEnabled()) { s_logger.debug(" ... waiting for file lock"); start = System.nanoTime(); } fileLock = indexInfoChannel.lock(); if (s_logger.isDebugEnabled()) { long end = System.nanoTime(); s_logger.debug(" ... got file lock in " + ((end - start) / 10e6f) + " ms"); } if (!checkVersion()) { setStatusFromFile(); } } result = lockWork.doWork(); return result; } catch (IOException e) { if (!lockWork.canRetry()) { s_logger.warn("This operation can not retry upon an IOException - it has to roll back to its previous state"); throw e; } if (retriesRemaining == 0) { s_logger.warn("No more channel open retries remaining"); throw e; } else { if (s_logger.isDebugEnabled()) { s_logger.debug("\n" + "Channel is closed. Will attempt to open it. \n" + " Retries remaining: " + retriesRemaining); } try { reopenChannels(); return doWithFileLock(lockWork, --retriesRemaining); } catch (Throwable ee) { s_logger.error("Channel reopen failed on index info files in: " + this.indexDirectory, ee); throw e; } } } finally { if (fileLock != null) { try { fileLock.release(); long end = System.nanoTime(); if (s_logger.isDebugEnabled()) { s_logger.debug(" ... released file lock after " + ((end - start) / 10e6f) + " ms"); } } catch (IOException e) { s_logger.warn("Failed to release file lock: " + e.getMessage(), e); } } } }
67. FileLockExclusiveReadLockStrategy#acquireExclusiveReadLock()
Project: camel
File: FileLockExclusiveReadLockStrategy.java
File: FileLockExclusiveReadLockStrategy.java
@Override public boolean acquireExclusiveReadLock(GenericFileOperations<File> operations, GenericFile<File> file, Exchange exchange) throws Exception { // must call super if (!super.acquireExclusiveReadLock(operations, file, exchange)) { return false; } File target = new File(file.getAbsoluteFilePath()); LOG.trace("Waiting for exclusive read lock to file: {}", target); FileChannel channel = null; RandomAccessFile randomAccessFile = null; boolean exclusive = false; FileLock lock = null; try { randomAccessFile = new RandomAccessFile(target, "rw"); // try to acquire rw lock on the file before we can consume it channel = randomAccessFile.getChannel(); StopWatch watch = new StopWatch(); while (!exclusive) { // timeout check if (timeout > 0) { long delta = watch.taken(); if (delta > timeout) { CamelLogger.log(LOG, readLockLoggingLevel, "Cannot acquire read lock within " + timeout + " millis. Will skip the file: " + target); // we could not get the lock within the timeout period, so return false return false; } } // get the lock using either try lock or not depending on if we are using timeout or not try { lock = timeout > 0 ? channel.tryLock() : channel.lock(); } catch (IllegalStateException ex) { } if (lock != null) { LOG.trace("Acquired exclusive read lock: {} to file: {}", lock, target); exclusive = true; } else { boolean interrupted = sleep(); if (interrupted) { // we were interrupted while sleeping, we are likely being shutdown so return false return false; } } } } catch (IOException e) { if (timeout == 0) { return false; } LOG.debug("Cannot acquire read lock. Will try again.", e); boolean interrupted = sleep(); if (interrupted) { return false; } } finally { // close channels if we did not grab the lock if (!exclusive) { IOHelper.close(channel, "while acquiring exclusive read lock for file: " + target, LOG); IOHelper.close(randomAccessFile, "while acquiring exclusive read lock for file: " + target, LOG); // and also must release super lock super.releaseExclusiveReadLockOnAbort(operations, file, exchange); } } // store read-lock state exchange.setProperty(asReadLockKey(file, Exchange.FILE_LOCK_EXCLUSIVE_LOCK), lock); exchange.setProperty(asReadLockKey(file, Exchange.FILE_LOCK_RANDOM_ACCESS_FILE), randomAccessFile); // we grabbed the lock return true; }
68. MiniThumbFile#getMiniThumbFromFile()
Project: BambooPlayer
File: MiniThumbFile.java
File: MiniThumbFile.java
protected synchronized byte[] getMiniThumbFromFile(long id, byte[] data) { RandomAccessFile r = miniThumbDataFile(); if (r == null) return null; long pos = id * BYTES_PER_MINTHUMB; FileLock lock = null; try { mBuffer.clear(); lock = mChannel.lock(pos, BYTES_PER_MINTHUMB, true); int size = mChannel.read(mBuffer, pos); if (size > 1 + 8 + 4) { mBuffer.position(9); int length = mBuffer.getInt(); if (size >= 1 + 8 + 4 + length && data.length >= length) { mBuffer.get(data, 0, length); return data; } } } catch (IOException ex) { Log.e("got exception when reading thumbnail id = %d, exception: %s", id, ex.getMessage()); } catch (RuntimeException ex) { Log.e("Got exception when reading thumbnail, id = %d, disk full or mount read-only? %s", id, ex.getClass().toString()); } finally { try { if (lock != null) lock.release(); } catch (IOException ex) { } } return null; }
69. MiniThumbFile#saveMiniThumbToFile()
Project: BambooPlayer
File: MiniThumbFile.java
File: MiniThumbFile.java
protected synchronized void saveMiniThumbToFile(byte[] data, long id, long magic) throws IOException { RandomAccessFile r = miniThumbDataFile(); if (r == null) return; long pos = id * BYTES_PER_MINTHUMB; FileLock lock = null; try { if (data != null) { if (data.length > BYTES_PER_MINTHUMB - HEADER_SIZE) return; mBuffer.clear(); mBuffer.put((byte) 1); mBuffer.putLong(magic); mBuffer.putInt(data.length); mBuffer.put(data); mBuffer.flip(); lock = mChannel.lock(pos, BYTES_PER_MINTHUMB, false); mChannel.write(mBuffer, pos); } } catch (IOException ex) { Log.e("couldn't save mini thumbnail data for %d; %s", id, ex.getMessage()); throw ex; } catch (RuntimeException ex) { Log.e("couldn't save mini thumbnail data for %d, disk full or mount read-only? %s", id, ex.getClass().toString()); } finally { try { if (lock != null) lock.release(); } catch (IOException ex) { } } }
70. FileSessionProvider#attach()
Project: asakusafw
File: FileSessionProvider.java
File: FileSessionProvider.java
private SessionMirror attach(String id, boolean create, boolean force) throws IOException { assert id != null; boolean completed = false; boolean delete = false; File path = idToFile(id); RandomAccessFile file = null; FileLock lock = null; try { LOG.debug("Opening session file: {}", path); file = new RandomAccessFile(path, "rw"); lock = acquireLock(id, path, file); State state = getSessionState(id, path, file); switch(state) { case INIT: if (create == false) { delete = true; throw new SessionException(id, Reason.NOT_EXIST); } else { createSession(path, file); } break; case CREATED: if (create) { throw new SessionException(id, Reason.ALREADY_EXIST); } break; case INVALID: if (force == false) { WGLOG.error("W01001", id, path); throw new SessionException(id, Reason.BROKEN); } break; default: throw new AssertionError(MessageFormat.format("Invalid state: {2} (id={0}, path={1})", id, path, state)); } completed = true; return new FileSessionMirror(id, path, file, lock); } catch (SessionException e) { throw e; } catch (IOException e) { WGLOG.error(e, "E01001", id, path); throw e; } finally { if (completed == false) { if (delete) { try { invalidate(path, file); } catch (IOException e) { WGLOG.warn(e, "W02002", id, path); } } if (lock != null) { try { lock.release(); } catch (IOException e) { WGLOG.warn(e, "W02001", id, path); } } if (file != null) { try { file.close(); } catch (IOException e) { WGLOG.warn(e, "W02002", id, path); } } if (delete) { if (path.delete() == false) { WGLOG.warn("W02002", id, path); } } } } }
71. FileLockNodeManager#lock()
Project: activemq-artemis
File: FileLockNodeManager.java
File: FileLockNodeManager.java
protected FileLock lock(final int liveLockPos) throws Exception { long start = System.currentTimeMillis(); while (!interrupted) { FileLock lock = null; try { lock = channel.tryLock(liveLockPos, 1, false); } catch (java.nio.channels.OverlappingFileLockException ex) { } if (lock == null) { try { Thread.sleep(500); } catch (InterruptedException e) { return null; } if (lockAcquisitionTimeout != -1 && (System.currentTimeMillis() - start) > lockAcquisitionTimeout) { throw new Exception("timed out waiting for lock"); } } else { return lock; } } // todo this is here because sometimes channel.lock throws a resource deadlock exception but trylock works, // need to investigate further and review FileLock lock; do { lock = channel.tryLock(liveLockPos, 1, false); if (lock == null) { try { Thread.sleep(500); } catch (InterruptedException e1) { } } if (interrupted) { interrupted = false; throw new IOException("Lock was interrupted"); } } while (lock == null); return lock; }