Java Code Examples for java.nio.channels.FileLock#release()

The following examples show how to use java.nio.channels.FileLock#release() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DataStorage.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isPreUpgradableLayout(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;
}
 
Example 2
Source File: FileWriteStream.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
public boolean unlock()
{
  try {
    FileLock lock = _fileLock;
    _fileLock = null;

    if (lock != null) {
      lock.release();

      return true;
    }

    return false;
  } catch (IOException e) {
    log.log(Level.FINE, e.toString(), e);
    return false;
  }
}
 
Example 3
Source File: Stream.java    From jphp with Apache License 2.0 6 votes vote down vote up
@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");
    }
}
 
Example 4
Source File: DocArchiveLockManager.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * unlock the previous locked file.
 * 
 * @param lockObj
 *            the object get from the lock.
 */
public void unlock( Object lockObj )
{
	if ( lockObj instanceof Lock )
	{
		Lock lock = (Lock) lockObj;
		FileLock fLock = lock.lock;
		FileChannel channel = fLock.channel( );
		try
		{
			fLock.release( );
		}
		catch ( Exception ex )
		{
			log.log( Level.FINE, "exception occus while release the lock",
					ex );
		}
		// after unlock the file, notify the waiting threads
		synchronized ( channel )
		{
			channel.notify( );
		}
		releaseChannel( lock.name );
	}
}
 
Example 5
Source File: FileReadStream.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
public boolean unlock()
{
  try {
    FileLock lock = _fileLock;
    _fileLock = null;

    if (lock != null) {
      lock.release();

      return true;
    }

    return false;
  } catch (IOException e) {
    log.log(Level.FINE, e.toString(), e);
    return false;
  }
}
 
Example 6
Source File: Storage.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * 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() throws IOException {
  FileLock firstLock = null;
  FileLock secondLock = null;
  try {
    firstLock = lock;
    if(firstLock == null) {
      firstLock = tryLock();
      if(firstLock == null)
        return true;
    }
    secondLock = tryLock();
    if(secondLock == null)
      return true;
  } finally {
    if(firstLock != null && firstLock != lock) {
      firstLock.release();
      firstLock.channel().close();
    }
    if(secondLock != null) {
      secondLock.release();
      secondLock.channel().close();
    }
  }
  return false;
}
 
Example 7
Source File: JournalKeeperState.java    From journalkeeper with Apache License 2.0 6 votes vote down vote up
public void init(Path path, List<URI> voters, Set<Integer> partitions, URI preferredLeader) throws IOException {
    Files.createDirectories(path.resolve(USER_STATE_PATH));
    InternalState internalState = new InternalState(new ConfigState(voters), partitions, preferredLeader);
    File lockFile = path.getParent().resolve(path.getFileName() + ".lock").toFile();
    try (RandomAccessFile raf = new RandomAccessFile(lockFile, "rw");
         FileChannel fileChannel = raf.getChannel()) {
        FileLock lock = fileChannel.tryLock();
        if (null == lock) {
            throw new ConcurrentModificationException(
                    String.format(
                            "Some other thread is operating the state files! State: %s.", path.toString()
                    ));
        } else {
            flushInternalState(internalStateFile(path), internalState);
            lock.release();
        }
    } finally {
        lockFile.delete();
    }
}
 
Example 8
Source File: FileLockNodeManager.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isBackupLive() throws Exception {
   FileLock liveAttemptLock;
   liveAttemptLock = tryLock(FileLockNodeManager.LIVE_LOCK_POS);
   if (liveAttemptLock == null) {
      return true;
   } else {
      liveAttemptLock.release();
      return false;
   }
}
 
Example 9
Source File: DiskStoreImpl.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
void closeLockFile() {
  FileLock myfl = this.fl;
  if (myfl != null) {
    try {
      FileChannel fc = myfl.channel();
      if (myfl.isValid()) {
        myfl.release();
      }
      fc.close();
    } catch (IOException ignore) {
    }
    this.fl = null;
  }
  File f = this.lockFile;
  if (f != null) {
    if (f.delete()) {
      if (logger.fineEnabled()) {
        logger.fine("Deleted lock file " + f);
      }
    } else if (f.exists()) {
      if (logger.fineEnabled()) {
        logger.fine("Could not delete lock file " + f);
      }
    }
  }
  logger.info(LocalizedStrings.DEBUG, "Unlocked disk store " + name); // added
                                                                      // to
                                                                      // help
                                                                      // debug
                                                                      // 41734
}
 
Example 10
Source File: IOUtils.java    From metrics with Apache License 2.0 5 votes vote down vote up
public static void closeQuietly(FileLock fileLock) {
    try {
        if (fileLock != null) {
            fileLock.release();
        }
    } catch (final IOException ioe) {
        // ignore
        ioe.printStackTrace();
    }

}
 
Example 11
Source File: AbstractModelLoader.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
protected void doStore(Context context, byte[] data, File file) {
    if (file == null) {
        return;
    }
    // Save
    try {
        File lockfile = new File(file.getAbsolutePath() + ".lock");
        if (!lockfile.exists()) {
            lockfile.createNewFile();
        }
        try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
             FileChannel channel = raf.getChannel()) {
            FileLock lock = channel.tryLock();
            if (lock == null) {
                throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file");
            }
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
                try (FileOutputStream outputFile = new FileOutputStream(file)) {
                    outputFile.write(data);
                }
            } finally {
                lock.release();
            }
        }
    } catch (Throwable e) {
        logger.error("Failed to save model cache file, will retry, cause: " + e.getMessage(), e);
    }
}
 
Example 12
Source File: Close.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
/**
 * 关闭文件锁
 *
 * @param lock 文件锁
 * @return
 */
public static Close close(final FileLock lock) {
    if (lock != null) {
        try {
            lock.release();
        } catch (IOException e) {
        }
    }
    return instance;
}
 
Example 13
Source File: StreamerUtils.java    From WandFix with MIT License 5 votes vote down vote up
public static void safeClose(FileLock closeable) {
    if (closeable != null) {
        try {
            if (Build.VERSION.SDK_INT > 18) {
                closeable.close();
            } else {
                closeable.release();
            }
        } catch (Throwable e) {
        }
    }
}
 
Example 14
Source File: FileLocking.java    From LearningOfThinkInJava with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception{
    FileOutputStream fos=new FileOutputStream("");
    FileLock fl=fos.getChannel().tryLock();
    if(fl!=null){
        System.out.println("Locked File");
        TimeUnit.MILLISECONDS.sleep(100);
        fl.release();
        System.out.println("Released Lock");
    }
    fos.close();
}
 
Example 15
Source File: AtlasFileLock.java    From AtlasForAndroid with MIT License 5 votes vote down vote up
public void unLock(File file) {
    if (file == null || this.mRefCountMap.containsKey(file.getAbsolutePath())) {
        FileLock fileLock = ((FileLockCount) this.mRefCountMap.get(file.getAbsolutePath())).mFileLock;
        if (fileLock != null && fileLock.isValid()) {
            try {
                if (RefCntDec(file.getAbsolutePath()) <= 0) {
                    fileLock.release();
                    Log.i(TAG, processName + " FileLock " + file.getAbsolutePath() + " SUC! ");
                }
            } catch (IOException e) {
            }
        }
    }
}
 
Example 16
Source File: Sharing.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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();
    }
}
 
Example 17
Source File: Sharing.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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();
    }
}
 
Example 18
Source File: Sharing.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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();
    }
}
 
Example 19
Source File: Sharing.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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();
    }
}
 
Example 20
Source File: JarClassLoader.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public JarClassLoader(final File file, final String jarName, byte[] jarBytes) throws IOException {
  Assert.assertTrue(file != null, "file cannot be null");
  Assert.assertTrue(jarName != null, "jarName cannot be null");
  FileLock tempLock = null;
  try {
    @SuppressWarnings("resource")
    FileInputStream fileInputStream = new FileInputStream(file);
    tempLock = fileInputStream.getChannel().lock(0, file.length(), true);

    try {
      this.logger = CacheFactory.getAnyInstance().getLogger();
    } catch (CacheClosedException ccex) {
      // That's okay, logging will just go to stdout/stderr.
    }

    trace("Acquired shared file lock w/ channel: " + tempLock.channel() + ", for JAR: " + file.getAbsolutePath());

    if (file.length() == 0) {
      throw new FileNotFoundException("JAR file was truncated prior to obtaining a lock: " + jarName);
    }

    final byte[] fileContent = getJarContent();
    if (!Arrays.equals(fileContent, jarBytes)) {
      throw new FileNotFoundException("JAR file: " + file.getAbsolutePath() + ", was modified prior to obtaining a lock: "
          + jarName);
    }
      
    if (!isValidJarContent(jarBytes)) {
      if (tempLock != null) {
        tempLock.release();
        tempLock.channel().close();
        trace("Prematurely releasing shared file lock due to bad content for JAR file: " + file.getAbsolutePath()
            + ", w/ channel: " + tempLock.channel());
      }
      throw new IllegalArgumentException("File does not contain valid JAR content: " + file.getAbsolutePath());
    }
    
    Assert.assertTrue(jarBytes != null, "jarBytes cannot be null");

    // Temporarily save the contents of the JAR file until they can be processed by the
    // loadClassesandRegisterFunctions() method.
    this.jarByteContent = jarBytes;

    if (messageDigest != null) {
      this.md5hash = messageDigest.digest(this.jarByteContent);
    } else {
      this.md5hash = null;
    }

    this.file = file;
    this.jarName = jarName;
    this.fileLock = tempLock;

  } catch (FileNotFoundException fnfex) {
    if (tempLock != null) {
      tempLock.release();
      tempLock.channel().close();
      trace("Prematurely releasing shared file lock due to file not found for JAR file: " + file.getAbsolutePath()
          + ", w/ channel: " + tempLock.channel());
    }
    throw fnfex;
  }
}