java.nio.channels.FileLock Java Examples

The following examples show how to use java.nio.channels.FileLock. 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: FileLockTable.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
void replace(FileLock fromLock, FileLock toLock) {
    // the lock must exist so there must be a list
    List<FileLockReference> list = lockMap.get(fileKey);
    assert list != null;

    synchronized (list) {
        for (int index=0; index<list.size(); index++) {
            FileLockReference ref = list.get(index);
            FileLock lock = ref.get();
            if (lock == fromLock) {
                ref.clear();
                list.set(index, new FileLockReference(toLock, queue, fileKey));
                locks.remove(fromLock);
                locks.add(toLock);
                break;
            }
        }
    }
}
 
Example #2
Source File: FileUtils.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Waits for a file lock for a given time, with a given frequency.
 * Does nothing if cannot lock after totalTime - to avoid deadlocks
 * @param f
 * @param time
 * @param totalTime
 */
public static void pauseForLock(File f, int frequency, int totalTime) throws Exception {
	
	// If file locked, wait for up to 2s
	int waited = 0;
	final FileOutputStream out = new FileOutputStream(f);
	try {
		FileLock lock = out.getChannel().tryLock();
		try {
			while(lock==null) {
				Thread.sleep(frequency);
				waited+=frequency;
				if (waited>=totalTime) break;
			}
		} finally {
			if (lock!=null) lock.release();
		}
	} finally {
		out.close();
	}
}
 
Example #3
Source File: Storage.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to acquire an exclusive lock on the storage.
 * 
 * @return A lock object representing the newly-acquired lock or
 * <code>null</code> if storage is already locked.
 * @throws IOException if locking fails.
 */
FileLock tryLock() throws IOException {
  File lockF = new File(root, STORAGE_FILE_LOCK);
  lockF.deleteOnExit();
  RandomAccessFile file = new RandomAccessFile(lockF, "rws");
  FileLock res = null;
  try {
    res = file.getChannel().tryLock();
  } catch(OverlappingFileLockException oe) {
    file.close();
    return null;
  } catch(IOException e) {
    LOG.error("Cannot create lock on " + lockF, e);
    file.close();
    throw e;
  }
  return res;
}
 
Example #4
Source File: DirectoryLockManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void removeInvalidLock(File lockDir) {
	try {
		boolean revokeLock = false;

		File lockedFile = new File(lockDir, LOCK_FILE_NAME);
		try (RandomAccessFile raf = new RandomAccessFile(lockedFile, "rw")) {
			FileLock fileLock = raf.getChannel().tryLock();

			if (fileLock != null) {
				logger.warn("Removing invalid lock {}", getLockedBy());
				fileLock.release();
				revokeLock = true;
			}
		} catch (OverlappingFileLockException exc) {
			// lock is still valid
		}

		if (revokeLock) {
			revokeLock();
		}
	} catch (IOException e) {
		logger.warn(e.toString(), e);
	}
}
 
Example #5
Source File: FileUtils.java    From logbook with MIT License 6 votes vote down vote up
/**
 * ファイルがロックされているかを確認します
 *
 * @param path ファイル
 * @return ロックされている場合true
 */
public static boolean isLocked(Path path) {
    if (!Files.isRegularFile(path)) {
        return false;
    }
    try (FileChannel fc = FileChannel.open(path,
            StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
        FileLock lock = fc.tryLock();
        if (lock != null) {
            lock.release();
            return false;
        } else {
            return true;
        }
    } catch (IOException e) {
        return true;
    }
}
 
Example #6
Source File: FileManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
protected synchronized void write(final byte[] bytes, final int offset, final int length,
        final boolean immediateFlush) {
    if (isLocking) {
        try {
            @SuppressWarnings("resource")
            final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel();
            /*
             * Lock the whole file. This could be optimized to only lock from the current file position. Note that
             * locking may be advisory on some systems and mandatory on others, so locking just from the current
             * position would allow reading on systems where locking is mandatory. Also, Java 6 will throw an
             * exception if the region of the file is already locked by another FileChannel in the same JVM.
             * Hopefully, that will be avoided since every file should have a single file manager - unless two
             * different files strings are configured that somehow map to the same file.
             */
            try (final FileLock lock = channel.lock(0, Long.MAX_VALUE, false)) {
                super.write(bytes, offset, length, immediateFlush);
            }
        } catch (final IOException ex) {
            throw new AppenderLoggingException("Unable to obtain lock on " + getName(), ex);
        }
    } else {
        super.write(bytes, offset, length, immediateFlush);
    }
}
 
Example #7
Source File: ExecUtil.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void lockProcess(String lockFileName) {
	if (!CommonUtil.isEmptyString(lockFileName)) {
		// https://stackoverflow.com/questions/7036108/prevent-launching-multiple-instances-of-a-java-application
		File file = new File(lockFileName);
		try {
			FileChannel fc = FileChannel.open(file.toPath(),
					StandardOpenOption.CREATE,
					StandardOpenOption.WRITE);
			FileLock lock = fc.tryLock();
			if (lock == null) {
				throw new RuntimeException("another instance is running");
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
 
Example #8
Source File: GlobalHotkeyListener.java    From ClipIt with MIT License 6 votes vote down vote up
public GlobalHotkeyListener(TipsFrame tipsFrame) {
    this.tipsFrame = tipsFrame;
    for (HotkeyType hotKey : HotkeyType.values()) {
        JIntellitype.getInstance().registerHotKey(hotKey.getIdentifier(), hotKey.getModifier(), hotKey.getKeycode());
    }
    // 禁止重复运行
    try {
        stream = new FileOutputStream(workingLockFile);
        FileLock fileLock = stream.getChannel().tryLock();
        if (fileLock == null) {
            System.out.println("working");
            System.exit(1);
        }
    } catch (FileNotFoundException ignore) {
    } catch (IOException e) {
        System.exit(1);
    }
}
 
Example #9
Source File: ChunkUtils.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private static long writeDataToFile(File file, ChunkBuffer data,
    long offset, boolean sync) {
  final Path path = file.toPath();
  return processFileExclusively(path, () -> {
    FileChannel channel = null;
    try {
      channel = open(path, WRITE_OPTIONS, NO_ATTRIBUTES);

      try (FileLock ignored = channel.lock()) {
        return writeDataToChannel(channel, data, offset);
      }
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    } finally {
      closeFile(channel, sync);
    }
  });
}
 
Example #10
Source File: FileLocks.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Gets an exclusive lock from a RandomAccessFile. Works because the file is writable.
 * @param from beginning of the locked region
 * @param size how many bytes to lock
 * @return A lock object representing the newly-acquired lock
 * @throws IOException if there is a problem creating the temporary file
 */
static FileLock getExclusiveLockFromRandomAccessFile(long from, long size) throws IOException {
    Path path = Files.createTempFile("foo", "txt");
    try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "rw");
        FileLock lock = file.getChannel()
            .lock(from, size, false)) {
        if (lock.isValid()) {
            LOG.debug("This is a valid exclusive lock");
            return lock;
        }
        return null;
    } catch (Exception e) {
        LOG.error(e.getMessage());
    }
    return null;
}
 
Example #11
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 #12
Source File: DexExtractor.java    From sbt-android-protify with Apache License 2.0 6 votes vote down vote up
private static <T> T withBlockingLock(File dexDir, File sourceApk, RunnableIO<T> r) throws IOException {
    final long currentCrc = getZipCrc(sourceApk);
    File lockFile = new File(dexDir, LOCK_FILE);
    RandomAccessFile lockRaf = new RandomAccessFile(lockFile, "rw");
    FileChannel lockChannel = null;
    FileLock cacheLock = null;
    try {
        lockChannel = lockRaf.getChannel();
        Log.v(TAG, "Waiting for lock on: " + lockFile.getAbsolutePath());
        cacheLock = lockChannel.lock();
        Log.v(TAG, "Locked " + lockFile.getPath());
        long l = lockRaf.length() >= (Long.SIZE / 8) ? lockRaf.readLong() : 0;
        long c = lockRaf.length() >= 2 * (Long.SIZE / 8) ? lockRaf.readLong() : 0;
        return r.run(c != currentCrc || l != getTimeStamp(sourceApk));
    } finally {
        lockRaf.seek(0);
        lockRaf.writeLong(getTimeStamp(sourceApk));
        lockRaf.writeLong(currentCrc);
        if (cacheLock != null)
            cacheLock.release();
        if (lockChannel != null)
            lockChannel.close();
        lockRaf.close();
        Log.v(TAG, "Unlocked " + lockFile.getPath());
    }
}
 
Example #13
Source File: FileLocks.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Trying to get a shared lock on a write-only FileChannel won't work.
 */
static void getReadLockFromOutputStream() throws IOException {
    Path path = Files.createTempFile("foo", "txt");
    try (FileOutputStream fis = new FileOutputStream(path.toFile());
        FileLock lock = fis.getChannel()
            .lock(0, Long.MAX_VALUE, true)) {
        LOG.debug("This won't happen");
    } catch (NonReadableChannelException e) {
        LOG.error("The channel obtained through a FileOutputStream isn't readable. " + "You can't obtain an shared lock on it!");
        throw e;
    }
}
 
Example #14
Source File: FileChannelImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public List<FileLock> removeAll() {
    synchronized(lockList) {
        List<FileLock> result = new ArrayList<FileLock>(lockList);
        lockList.clear();
        return result;
    }
}
 
Example #15
Source File: JimfsFileChannel.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Override
public FileLock tryLock(long position, long size, boolean shared) throws IOException {
  checkLockArguments(position, size, shared);

  // tryLock is not interruptible
  return new FakeFileLock(this, position, size, shared);
}
 
Example #16
Source File: RaftStorageDirectory.java    From ratis with Apache License 2.0 5 votes vote down vote up
/**
 * Lock storage to provide exclusive access.
 *
 * <p> Locking is not supported by all file systems.
 * E.g., NFS does not consistently support exclusive locks.
 *
 * <p> If locking is supported we guarantee exclusive access to the
 * storage directory. Otherwise, no guarantee is given.
 *
 * @throws IOException if locking fails
 */
public void lock() throws IOException {
  FileLock newLock = tryLock();
  if (newLock == null) {
    String msg = "Cannot lock storage " + this.root
        + ". The directory is already locked";
    LOG.info(msg);
    throw new IOException(msg);
  }
  // Don't overwrite lock until success - this way if we accidentally
  // call lock twice, the internal state won't be cleared by the second
  // (failed) lock attempt
  lock = newLock;
}
 
Example #17
Source File: LogFileWriter.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
private long append(FlatBufferBuilder h, FlatBufferBuilder c) throws IOException {
    ByteBuffer bb1 = h.dataBuffer();
    ByteBuffer bb2 = (c == null ? null : c.dataBuffer());

    try (RandomAccessFile f = new RandomAccessFile(file, "rw"); FileChannel fc = f.getChannel(); FileLock lock = fc.lock()) {
        //TODO can we make this more efficient - use a single byte buffer?

        //Seek to end for append
        f.seek(f.length());
        long startPos = f.getFilePointer();

        //Write header - length of SystemInfo header, length of content header
        ByteBuffer header = ByteBuffer.allocate(8); //8 bytes = 2x 4 byte integers
        int l1 = bb1.remaining();
        int l2 = bb2 == null ? 0 : bb2.remaining();
        header.putInt(l1);
        header.putInt(l2);
        header.flip();

        //System.out.println("Lengths - header, content: " + l1 + ", " + l2);

        int w1 = fc.write(header);
        int w2 = fc.write(bb1);
        int w3 = bb2 == null ? 0 : fc.write(bb2);
        long total = w1 + w2 + w3;
        //System.out.println("Wrote " + total + " bytes starting at position " + startPos);
        //System.out.println("Post writing file length: " + file.length());
        return total;
    }
}
 
Example #18
Source File: CrossProcessLock.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Create and return a lock that is exclusive across processes. If another process has the lock
 * then this call will block until it is released.
 *
 * @param lockName the lockname is global across all processes of an app
 * @return a CrossProcessLock if success. If the lock failed to acquire (maybe due to disk full or
 *     other unexpected and unsupported permissions) then null will be returned.
 */
static CrossProcessLock acquire(Context appContext, String lockName) {
  FileChannel channel = null;
  FileLock lock = null;
  try {
    File file = new File(appContext.getFilesDir(), lockName);
    channel = new RandomAccessFile(file, "rw").getChannel();
    // Use the file channel to create a lock on the file.
    // This method blocks until it can retrieve the lock.
    lock = channel.lock();
    return new CrossProcessLock(channel, lock);
  } catch (IOException | Error e) {
    // Certain conditions can cause file locking to fail, such as out of disk or bad permissions.
    // In any case, the acquire will fail and return null instead of a held lock.
    // NOTE: In Java 7 & 8, FileKey creation failure might wrap IOException into Error. See
    // https://bugs.openjdk.java.net/browse/JDK-8025619 for details.
    Log.e(TAG, "encountered error while creating and acquiring the lock, ignoring", e);

    // Clean up any dangling resources
    if (lock != null) {
      try {
        lock.release();
      } catch (IOException e2) {
        // nothing to do here
      }
    }
    if (channel != null) {
      try {
        channel.close();
      } catch (IOException e3) {
        // nothing to do here
      }
    }

    return null;
  }
}
 
Example #19
Source File: FileUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Releases the given lock quietly no logging, no exception
 *
 * @param lock the lock to release
 */
public static void releaseQuietly(final FileLock lock) {
    if (null != lock) {
        try {
            lock.release();
        } catch (final IOException io) {
            /*IGNORE*/
        }
    }
}
 
Example #20
Source File: FileChannelLockingTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_lockReadWrite() throws IOException {
    // Acquire an exclusive lock across the entire file.
    FileLock flock = readWriteChannel.lock();
    if (flock != null) {
        flock.release();
    }
}
 
Example #21
Source File: FileChannelImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected void implCloseChannel() throws IOException {
    // Release and invalidate any locks that we still hold
    if (fileLockTable != null) {
        for (FileLock fl: fileLockTable.removeAll()) {
            synchronized (fl) {
                if (fl.isValid()) {
                    nd.release(fd, fl.position(), fl.size());
                    ((FileLockImpl)fl).invalidate();
                }
            }
        }
    }

    // signal any threads blocked on this channel
    threads.signalAndWait();

    if (parent != null) {

        // Close the fd via the parent stream's close method.  The parent
        // will reinvoke our close method, which is defined in the
        // superclass AbstractInterruptibleChannel, but the isOpen logic in
        // that method will prevent this method from being reinvoked.
        //
        ((java.io.Closeable)parent).close();
    } else {
        nd.close(fd);
    }

}
 
Example #22
Source File: AtlasFileLock.java    From atlas with Apache License 2.0 5 votes vote down vote up
private int RefCntInc(String name, FileLock fileLock, RandomAccessFile fOs, FileChannel fChannel){
	Integer val = 0;
	
	if (mRefCountMap.containsKey(name)){
		val = mRefCountMap.get(name).mRefCount++;
	} else {
		val = 1;
		FileLockCount newFileLockCount = new FileLockCount(fileLock, val, fOs, fChannel);
		mRefCountMap.put(name, newFileLockCount);
	}

	return val;
}
 
Example #23
Source File: OffsetCheckpoint.java    From kcache with Apache License 2.0 5 votes vote down vote up
public OffsetCheckpoint(final String checkpointDir, String topic) throws IOException {
    File baseDir = baseDir(checkpointDir, topic);
    this.file = new File(baseDir, CHECKPOINT_FILE_NAME);
    lock = new Object();

    final File lockFile = new File(baseDir, LOCK_FILE_NAME);
    final FileChannel channel = FileChannel.open(lockFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
    final FileLock fileLock = tryLock(channel);
    if (fileLock == null) {
        channel.close();
        throw new IOException("Could not obtain file lock");
    }
    this.channel = channel;
    this.fileLock = fileLock;
}
 
Example #24
Source File: GoConfigFileWriter.java    From gocd with Apache License 2.0 5 votes vote down vote up
public synchronized void writeToConfigXmlFile(String content) {
    try (
            RandomAccessFile randomAccessFile = new RandomAccessFile(systemEnvironment.getCruiseConfigFile(), "rw");
            FileChannel channel = randomAccessFile.getChannel();
            FileLock lock = channel.lock();
    ) {
        randomAccessFile.seek(0);
        randomAccessFile.setLength(0);
        final byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        channel.transferFrom(Channels.newChannel(new ByteArrayInputStream(bytes)), 0, bytes.length);
    } catch (IOException e) {
        LOGGER.error("Error occured when writing config XML to file", e);
        throw new UncheckedIOException(e);
    }
}
 
Example #25
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 #26
Source File: FileChannelImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public List<FileLock> removeAll() {
    synchronized(lockList) {
        List<FileLock> result = new ArrayList<FileLock>(lockList);
        lockList.clear();
        return result;
    }
}
 
Example #27
Source File: FlexibleFileWriter.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
private synchronized void syncWrite(ByteBuffer buf) throws IOException {
    FileLock lock = fileChannel.lock();
    try {
        fileChannel.write(buf);
    } finally {
        lock.release();
    }
}
 
Example #28
Source File: Launcher.java    From xyTalk-pc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
    * 通过文件锁来判断程序是否正在运行
    *
    * @return 如果正在运行返回true,否则返回false
    */
   @SuppressWarnings("resource")
private static boolean isApplicationRunning()
   {
       boolean rv = false;
       try
       {
           String path = appFilesBasePath + System.getProperty("file.separator") + "appLock";
           File dir = new File(path);
           if (!dir.exists())
           {
               dir.mkdirs();
           }

           File lockFile = new File(path + System.getProperty("file.separator") + "appLaunch.lock");
           if (!lockFile.exists())
           {
               lockFile.createNewFile();
           }

           //程序名称
           RandomAccessFile fis = new RandomAccessFile(lockFile.getAbsolutePath(), "rw");
           FileChannel fileChannel = fis.getChannel();
           FileLock fileLock = fileChannel.tryLock();
           if (fileLock == null)
           {
               System.out.println("程序已在运行.");
               rv = true;
           }
       }
       catch (FileNotFoundException e1)
       {
           e1.printStackTrace();
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
       return rv;
   }
 
Example #29
Source File: StoredObjectServiceTest.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
@Ignore //this test does not work on ubuntu (i.e. travis-ci) but on windows
@Test(expected = IOException.class)
public void testFailedWrite() throws IOException {
	File file = folder.newFile();
	file.delete();
	StoredObjectService service = new StoredObjectService(file);
	try (RandomAccessFile raf = new RandomAccessFile(file, "rw");
		FileChannel channel = raf.getChannel();
		FileLock ignored = channel.lock()) {
		service.store("foo");
		fail();
	}
}
 
Example #30
Source File: LockingMappedFiles.java    From LearningOfThinkInJava with Apache License 2.0 5 votes vote down vote up
public void run(){
    try{
        FileLock fl=fc.lock(start,end,false);
        System.out.println("Locked: "+start+" to"+end);
        while (buff.position()<buff.limit()-1){
            buff.put((byte)(buff.get()+1));
        }
        fl.release();
        System.out.println("Released: "+start+" to "+end);
    }catch (IOException e){
        throw new RuntimeException(e);
    }
}