java.nio.channels.FileChannel.lock()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(218)

本文整理了Java中java.nio.channels.FileChannel.lock()方法的一些代码示例,展示了FileChannel.lock()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。FileChannel.lock()方法的具体详情如下:
包路径:java.nio.channels.FileChannel
类名称:FileChannel
方法名:lock

FileChannel.lock介绍

[英]Obtains an exclusive lock on this file.

This is a convenience method for acquiring a maximum length lock on a file. It is equivalent to: fileChannel.lock(0L, Long.MAX_VALUE, false);
[中]获取此文件的独占锁。
这是获取文件最大长度锁的方便方法。它相当于:fileChannel。锁定(0L,长。最大值,假);

代码示例

代码示例来源:origin: wildfly/wildfly

@Override
public FileLock lock(long position, long size, boolean shared) throws IOException {
  return channel.lock(position, size, shared);
}

代码示例来源:origin: wildfly/wildfly

public FileLock lock(final long position, final long size, final boolean shared) throws IOException {
  return delegate.lock(position, size, shared);
}

代码示例来源:origin: stackoverflow.com

FileInputStream in = new FileInputStream(file);
try {
  java.nio.channels.FileLock lock = in.getChannel().lock();
  try {
    Reader reader = new InputStreamReader(in, charset);
    ...
  } finally {
    lock.release();
  }
} finally {
  in.close();
}

代码示例来源:origin: robolectric/robolectric

private void whileLocked(Runnable runnable) {
 File lockFile = new File(System.getProperty("user.home"), ".robolectric-download-lock");
 try (RandomAccessFile raf = new RandomAccessFile(lockFile, "rw")) {
  try (FileChannel channel = raf.getChannel()) {
   try (FileLock ignored = channel.lock()) {
    runnable.run();
   }
  }
 } catch (IOException e) {
  throw new IllegalStateException("Couldn't create lock file " + lockFile, e);
 } finally {
  lockFile.delete();
 }
}

代码示例来源:origin: cmusphinx/sphinx4

/** Lock the test suite so we can manipulate the set of tests */
private void lock() throws IOException {
  RandomAccessFile raf = new RandomAccessFile(lockFile, "rw");
  lock = raf.getChannel().lock();
  raf.close();
}

代码示例来源:origin: apache/geode

protected int currentValue() throws IOException {
  try (FileOutputStream out = new FileOutputStream(lockFile)) {
   java.nio.channels.FileLock lock = out.getChannel().lock();
   try {
    String fileContents = FileUtils.readFileToString(dataFile, Charsets.UTF_8);
    return Integer.valueOf(fileContents);
   } finally {
    lock.release();
   }
  }
 }
}

代码示例来源:origin: apache/geode

public void countDown() throws IOException {
 try (FileOutputStream out = new FileOutputStream(lockFile)) {
  java.nio.channels.FileLock lock = out.getChannel().lock();
  try {
   String fileContents = FileUtils.readFileToString(dataFile, Charsets.UTF_8);
   int currentValue = Integer.valueOf(fileContents);
   int newValue = currentValue - 1;
   FileUtils.writeStringToFile(dataFile, String.valueOf(newValue), Charsets.UTF_8);
  } finally {
   lock.release();
  }
 }
}

代码示例来源:origin: apache/geode

public FileBasedCountDownLatch(int count) throws IOException {
 lockFile = File.createTempFile("CountDownLatchLock", ".txt");
 dataFile = File.createTempFile("CountDownLatchData", ".txt");
 try (FileOutputStream out = new FileOutputStream(lockFile)) {
  java.nio.channels.FileLock lock = out.getChannel().lock();
  try {
   FileUtils.writeStringToFile(dataFile, String.valueOf(count), Charsets.UTF_8);
  } finally {
   lock.release();
  }
 }
 lockFile.deleteOnExit();
}

代码示例来源:origin: Tencent/tinker

numAttempts++;
try {
  localFileLock = outputStream.getChannel().lock();
  isGetLockSuccess = (localFileLock != null);
  if (isGetLockSuccess) {

代码示例来源:origin: GoogleContainerTools/jib

/**
 * Deserializes a JSON file via a JSON object template with a shared lock on the file
 *
 * @param <T> child type of {@link JsonTemplate}
 * @param jsonFile a file containing a JSON string
 * @param templateClass the template to deserialize the string to
 * @return the template filled with the values parsed from {@code jsonFile}
 * @throws IOException if an error occurred during reading the file or parsing the JSON
 */
public static <T extends JsonTemplate> T readJsonFromFileWithLock(
  Path jsonFile, Class<T> templateClass) throws IOException {
 // channel is closed by inputStream.close()
 FileChannel channel = FileChannel.open(jsonFile, StandardOpenOption.READ);
 channel.lock(0, Long.MAX_VALUE, true); // shared lock, released by channel close
 try (InputStream inputStream = Channels.newInputStream(channel)) {
  return objectMapper.readValue(inputStream, templateClass);
 }
}

代码示例来源:origin: runelite/runelite

private synchronized void saveToFile() throws IOException
{
  propertiesFile.getParentFile().mkdirs();
  try (FileOutputStream out = new FileOutputStream(propertiesFile))
  {
    final FileLock lock = out.getChannel().lock();
    try
    {
      properties.store(new OutputStreamWriter(out, Charset.forName("UTF-8")), "RuneLite configuration");
    }
    finally
    {
      lock.release();
    }
  }
}

代码示例来源:origin: Netflix/genie

/**
   * {@inheritDoc}
   */
  @Override
  public void lock() throws LockException {
    try {
      nioFileLock = fileChannel.lock();
    } catch (Exception e) {
      throw new LockException("Error locking file ", e);
    }
  }
}

代码示例来源:origin: GoogleContainerTools/jib

/**
 * Acquires an exclusive {@link FileLock} on the {@code file} and opens an {@link OutputStream} to
 * write to it. The file will be created if it does not exist, or truncated to length 0 if it does
 * exist. The {@link OutputStream} must be closed to release the lock.
 *
 * <p>The locking mechanism should not be used as a concurrency management feature. Rather, this
 * should be used as a way to prevent concurrent writes to {@code file}. Concurrent attempts to
 * lock {@code file} will result in {@link OverlappingFileLockException}s.
 *
 * @param file the file to write to
 * @return an {@link OutputStream} that writes to the file
 * @throws IOException if an I/O exception occurs
 */
public static OutputStream newLockingOutputStream(Path file) throws IOException {
 EnumSet<StandardOpenOption> createOrTruncate =
   EnumSet.of(
     StandardOpenOption.CREATE,
     StandardOpenOption.WRITE,
     StandardOpenOption.TRUNCATE_EXISTING);
 // Channel is closed by outputStream.close().
 FileChannel channel = FileChannel.open(file, createOrTruncate);
 // Lock is released when channel is closed.
 channel.lock();
 return Channels.newOutputStream(channel);
}

代码示例来源:origin: gocd/gocd

public synchronized 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);
      }
    }
  }
}

代码示例来源:origin: android-hacker/VirtualXposed

public boolean LockExclusive(File targetFile) {
  if (targetFile == null) {
    return false;
  }
  try {
    File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
    if (!lockFile.exists()) {
      lockFile.createNewFile();
    }
    RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile.getAbsolutePath(), "rw");
    FileChannel channel = randomAccessFile.getChannel();
    java.nio.channels.FileLock lock = channel.lock();
    if (!lock.isValid()) {
      return false;
    }
    RefCntInc(lockFile.getAbsolutePath(), lock, randomAccessFile, channel);
    return true;
  } catch (Exception e) {
    return false;
  }
}

代码示例来源:origin: neo4j/neo4j

public static void main( String[] args ) throws IOException
  {
    Path path = Paths.get( args[0] );
    try ( FileChannel channel = FileChannel.open( path, StandardOpenOption.READ, StandardOpenOption.WRITE );
       java.nio.channels.FileLock lock = channel.lock() )
    {
      System.out.println( LOCKED_OUTPUT );
      System.out.flush();
      System.in.read();
    }
  }
}

代码示例来源:origin: apache/ignite

@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();
    }
  }
});

代码示例来源:origin: apache/ignite

@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();
    }
  }
});

代码示例来源:origin: gocd/gocd

@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();
  }
}

代码示例来源:origin: oblac/jodd

@Test
  @EnabledOnOs({OS.WINDOWS})  // on windows host, test is successful. on linux host no io-exception is thrown
  void testDeleteFileTree_not_successful() throws Exception {
    assumeTrue(baseDir_Not_Successful.exists());
    assumeTrue(locked_file.exists());
    // When you use FileLock, it is purely advisory—acquiring a lock on a file may not stop you from doing anything:
    // reading, writing, and deleting a file may all be possible even when another process has acquired a lock.
    // Sometimes, a lock might do more than this on a particular platform, but this behavior is unspecified,
    // and relying on more than is guaranteed in the class documentation is a recipe for failure.
    try (RandomAccessFile randomAccessFile = new RandomAccessFile(locked_file, "rw");
       FileLock lock = randomAccessFile.getChannel().lock())
    {
      assumeTrue(lock.isValid(), locked_file.getAbsolutePath() + " is NOT locked...");
      // asserts
      IOException expectedException = assertThrows(
        IOException.class, () -> PathUtil.deleteFileTree(baseDir_Not_Successful.toPath()));
      assertTrue(expectedException instanceof FileSystemException);
      assertEquals(locked_file.getAbsolutePath(), ((FileSystemException)expectedException).getFile());
    }
  }
}

相关文章