Example usage for java.nio.channels FileChannel lock

List of usage examples for java.nio.channels FileChannel lock

Introduction

In this page you can find the example usage for java.nio.channels FileChannel lock.

Prototype

public final FileLock lock() throws IOException 

Source Link

Document

Acquires an exclusive lock on this channel's file.

Usage

From source file:org.cyclop.service.common.FileStorage.java

private FileChannel lock(Path histPath, FileChannel channel) throws IOException {
    LOG.debug("Trying to log file: {}", histPath);
    long start = System.currentTimeMillis();
    String lastExMessage = null;/*from w w w .jav a  2 s.  com*/
    FileChannel lockChannel = null;
    while (lockChannel == null && System.currentTimeMillis() - start < config.fileStore.lockWaitTimeoutMillis) {
        try {
            FileLock lock = channel.lock();
            lockChannel = lock.channel();
        } catch (FileLockInterruptionException | OverlappingFileLockException e) {
            lockRetryCount.incrementAndGet();
            lastExMessage = e.getMessage();
            LOG.debug("File lock on '{}' cannot be obtained (retrying operation): {}", histPath, lastExMessage);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
                Thread.interrupted();
            }
        }
    }
    if (lockChannel == null) {
        throw new ServiceException("File lock on '" + histPath + "' cannot be obtained: " + lastExMessage);
    }

    return lockChannel;
}

From source file:com.thoughtworks.go.config.GoConfigDataSource.java

public synchronized GoConfigSaveResult writeWithLock(UpdateConfigCommand updatingCommand,
        GoConfigHolder configHolder) {//from   w  w w .j a v  a 2s  . c o  m
    FileChannel channel = null;
    FileOutputStream outputStream = null;
    FileLock lock = null;
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
        channel = randomAccessFile.getChannel();
        lock = channel.lock();

        // Need to convert to xml before we try to write it to the config file.
        // If our cruiseConfig fails XSD validation, we don't want to write it incorrectly.
        String configAsXml = getModifiedConfig(updatingCommand, configHolder);

        randomAccessFile.seek(0);
        randomAccessFile.setLength(0);
        outputStream = new FileOutputStream(randomAccessFile.getFD());
        LOGGER.info(String.format("[Configuration Changed] Saving updated configuration."));
        IOUtils.write(configAsXml, outputStream);
        ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder)
                ? ConfigSaveState.MERGED
                : ConfigSaveState.UPDATED;
        return new GoConfigSaveResult(internalLoad(configAsXml, getConfigUpdatingUser(updatingCommand)),
                configSaveState);
    } catch (ConfigFileHasChangedException e) {
        LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: "
                + e.getMessage(), e);
        throw e;
    } catch (GoConfigInvalidException e) {
        LOGGER.warn("Configuration file is invalid: " + e.getMessage(), e);
        throw bomb(e.getMessage(), e);
    } catch (Exception e) {
        LOGGER.error("Configuration file is not valid: " + e.getMessage(), e);
        throw bomb(e.getMessage(), 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);
            }
        }
        LOGGER.debug("[Config Save] Done writing with lock");
    }
}

From source file:com.linkedin.helix.store.file.FilePropertyStore.java

@Override
public void updatePropertyUntilSucceed(String key, DataUpdater<T> updater, boolean createIfAbsent) {
    String path = getPath(key);//w w  w .  j  a v  a2s  .  c o m
    File file = new File(path);
    RandomAccessFile raFile = null;
    FileLock fLock = null;

    try {
        _readWriteLock.writeLock().lock();
        if (!file.exists()) {
            FileUtils.touch(file);
        }

        raFile = new RandomAccessFile(file, "rw");
        FileChannel fChannel = raFile.getChannel();
        fLock = fChannel.lock();

        T current = getProperty(key);
        T update = updater.update(current);
        setProperty(key, update);
    } catch (Exception e) {
        logger.error("fail to updatePropertyUntilSucceed, path:" + path, e);
    } finally {
        _readWriteLock.writeLock().unlock();
        try {
            if (fLock != null && fLock.isValid()) {
                fLock.release();
            }

            if (raFile != null) {
                raFile.close();
            }
        } catch (IOException e) {
            logger.error("fail to close file, path:" + path, e);
        }
    }
}

From source file:com.linkedin.helix.store.file.FilePropertyStore.java

@Override
public boolean compareAndSet(String key, T expected, T update, Comparator<T> comparator,
        boolean createIfAbsent) {
    String path = getPath(key);/*from   www  .j  a  va  2s .  c  o  m*/
    File file = new File(path);
    //    FileInputStream fin = null;
    //    FileOutputStream fout = null;
    RandomAccessFile raFile = null;
    FileLock fLock = null;

    try {
        _readWriteLock.writeLock().lock();

        if (createIfAbsent) {
            file.createNewFile();
        }

        //      fin = new FileInputStream(file);
        //      FileChannel fChannel = fin.getChannel();
        raFile = new RandomAccessFile(file, "rw");
        FileChannel fChannel = raFile.getChannel();
        fLock = fChannel.lock();

        T current = getProperty(key);
        if (comparator.compare(current, expected) == 0) {
            //        fout = new FileOutputStream(file);
            //
            //        byte[] bytes = _serializer.serialize(update);
            //        fout.write(bytes);
            setProperty(key, update);
            return true;
        }

        return false;
    } catch (FileNotFoundException e) {
        logger.error("fail to compareAndSet. path:" + path, e);
        return false;
    } catch (Exception e) {
        logger.error("fail to compareAndSet. path:" + path, e);
        return false;
    } finally {
        _readWriteLock.writeLock().unlock();
        try {
            if (fLock != null && fLock.isValid()) {
                fLock.release();
            }

            if (raFile != null) {
                raFile.close();
            }

            //        if (fin != null)
            //        {
            //          fin.close();
            //        }
            //
            //        if (fout != null)
            //        {
            //          fout.close();
            //        }
        } catch (IOException e) {
            logger.error("fail to close file. path:" + path, e);
        }
    }

}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

@Deprecated
public void releaseLocks() {
    l.trace("Trying to check file locks ");
    try {/*from  w  w  w  .  ja  va2  s  .c  o  m*/
        Collection c = FileUtils.listFiles(new File(Shared.workingDirectory), null, true);
        Object[] arr = c.toArray();
        for (int i = 0; i < arr.length; i++) {
            l.trace("Trying lock for: " + ((File) arr[i]).getAbsolutePath());
            // Get a file channel for the file
            File file = ((File) arr[i]);
            FileChannel 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.
            //FileLock lock = channel.lock();
            // Try acquiring the lock without blocking. This method returns
            // null or throws an exception if the file is already locked.
            FileLock lock = null;
            try {
                lock = channel.lock();
            } catch (OverlappingFileLockException ex) {
                l.trace("Lock already exists", ex);
            }
            if (lock == null) {
                l.trace("Lock failed - someone else holds lock");
            } else {
                l.trace("Lock shared: " + lock.isShared() + " Lock valid: " + lock.isValid());
                lock.release();
                l.trace("Lock release OK");
                try {
                    if (!file.delete()) {
                        throw new IOException();
                    }
                } catch (Exception e) {
                    l.trace("Delete failed", e);
                }
            }
        }
        //Thread.sleep(25000);

    } catch (Exception e) {
        // File is already locked in this thread or virtual machine
        l.trace("File lock problem", e);
    }
}

From source file:org.apache.camel.component.file.strategy.FileLockExclusiveReadLockStrategy.java

public boolean acquireExclusiveReadLock(GenericFileOperations<File> operations, GenericFile<File> file,
        Exchange exchange) throws Exception {
    File target = new File(file.getAbsoluteFilePath());

    if (LOG.isTraceEnabled()) {
        LOG.trace("Waiting for exclusive read lock to file: " + target);
    }//from w  w  w. j a  v  a2 s  .co m

    try {
        // try to acquire rw lock on the file before we can consume it
        FileChannel channel = new RandomAccessFile(target, "rw").getChannel();

        boolean exclusive = false;
        StopWatch watch = new StopWatch();

        while (!exclusive) {
            // timeout check
            if (timeout > 0) {
                long delta = watch.taken();
                if (delta > timeout) {
                    LOG.warn("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) {
                // Also catch the OverlappingFileLockException here. Do nothing here                    
            }
            if (lock != null) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Acquired exclusive read lock: " + lock + " to file: " + target);
                }
                lockFileName = target.getName();
                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) {
        // must handle IOException as some apps on Windows etc. will still somehow hold a lock to a file
        // such as AntiVirus or MS Office that has special locks for it's supported files
        if (timeout == 0) {
            // if not using timeout, then we cant retry, so rethrow
            throw e;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Cannot acquire read lock. Will try again.", e);
        }
        boolean interrupted = sleep();
        if (interrupted) {
            // we were interrupted while sleeping, we are likely being shutdown so return false
            return false;
        }
    }

    return true;
}

From source file:com.socialmarketing.config.ApplicationPrefs.java

/**
 * Initializes preferences//  www. j av  a  2 s.  c om
 *
 * @param context ServletContext
 */
public void initializePrefs(ServletContext context) {
    LOG.info("Initializing...");
    // Load the application node name, if any
    try {
        Properties instanceProperties = new Properties();
        instanceProperties.load(context.getResourceAsStream("/WEB-INF/instance.property"));
        node = instanceProperties.getProperty("node", DEFAULT_NODE);
        LOG.info("Node: " + node);
    } catch (Exception e) {
        LOG.info("Default Node: " + DEFAULT_NODE);
        node = DEFAULT_NODE;
    }
    // Determine the file library
    String fileLibrary = retrieveFileLibraryLocation(context);
    if (fileLibrary != null) {
        loadProperties(fileLibrary);
        this.add(FILE_LIBRARY_PATH, fileLibrary);
        configureDebug();
        // verifyKey(context, fileLibrary);
        // configureConnectionPool(context);
        // configureFreemarker(context);
        // configureWebdavManager(context);
        // configureSystemSettings(context);
        // configureCache(context);
        if (isConfigured()) {
            if (ApplicationVersion.isOutOfDate(this)) {
                LOG.info("Upgrade triggered... obtaining lock to continue");
                // Use a lock file to to start upgrading
                File upgradeLockFile = new File(fileLibrary + "upgrade.lock");
                FileChannel fileChannel = null;
                FileLock fileLock = null;
                try {
                    // Configure the file for locking
                    fileChannel = new RandomAccessFile(upgradeLockFile, "rw").getChannel();
                    // Use fileChannel.lock which blocks until the lock is obtained
                    fileLock = fileChannel.lock();
                    // Reload the prefs to make sure the upgrade isn't already complete
                    loadProperties(fileLibrary);
                    if (ApplicationVersion.isOutOfDate(this)) {
                        // The application needs an update
                        LOG.info("Installed version " + ApplicationVersion.getInstalledVersion(this)
                                + " will be upgraded to " + ApplicationVersion.VERSION);
                        //         performUpgrade(context);
                    }
                } catch (Exception e) {
                    LOG.error("initializePrefs-> performUpgrade", e);
                } finally {
                    try {
                        if (fileLock != null) {
                            fileLock.release();
                        }
                        if (fileChannel != null) {
                            fileChannel.close();
                        }
                    } catch (Exception eclose) {
                        LOG.error("initializePrefs-> lock", eclose);
                    }
                }
            }
            if (!ApplicationVersion.isOutOfDate(this)) {
                // Start the services now that everything is ready
                initializeServices(context);
            }
        }
    }
    configureDefaultBehavior(context);
    loadApplicationDictionaries(context);
}

From source file:com.concursive.connect.config.ApplicationPrefs.java

/**
 * Initializes preferences/*w w w .j a v  a2  s.  c  o m*/
 *
 * @param context ServletContext
 */
public void initializePrefs(ServletContext context) {
    LOG.info("Initializing...");
    // Load the application node name, if any
    try {
        Properties instanceProperties = new Properties();
        instanceProperties.load(context.getResourceAsStream("/WEB-INF/instance.property"));
        node = instanceProperties.getProperty("node", DEFAULT_NODE);
        LOG.info("Node: " + node);
    } catch (Exception e) {
        LOG.info("Default Node: " + DEFAULT_NODE);
        node = DEFAULT_NODE;
    }
    // Determine the file library
    String fileLibrary = retrieveFileLibraryLocation(context);
    if (fileLibrary != null) {
        loadProperties(fileLibrary);
        this.add(FILE_LIBRARY_PATH, fileLibrary);
        configureDebug();
        verifyKey(context, fileLibrary);
        configureConnectionPool(context);
        configureFreemarker(context);
        configureWebdavManager(context);
        configureSystemSettings(context);
        configureCache(context);
        if (isConfigured()) {
            if (ApplicationVersion.isOutOfDate(this)) {
                LOG.info("Upgrade triggered... obtaining lock to continue");
                // Use a lock file to to start upgrading
                File upgradeLockFile = new File(fileLibrary + "upgrade.lock");
                FileChannel fileChannel = null;
                FileLock fileLock = null;
                try {
                    // Configure the file for locking
                    fileChannel = new RandomAccessFile(upgradeLockFile, "rw").getChannel();
                    // Use fileChannel.lock which blocks until the lock is obtained
                    fileLock = fileChannel.lock();
                    // Reload the prefs to make sure the upgrade isn't already complete
                    loadProperties(fileLibrary);
                    if (ApplicationVersion.isOutOfDate(this)) {
                        // The application needs an update
                        LOG.info("Installed version " + ApplicationVersion.getInstalledVersion(this)
                                + " will be upgraded to " + ApplicationVersion.VERSION);
                        performUpgrade(context);
                    }
                } catch (Exception e) {
                    LOG.error("initializePrefs-> performUpgrade", e);
                } finally {
                    try {
                        if (fileLock != null) {
                            fileLock.release();
                        }
                        if (fileChannel != null) {
                            fileChannel.close();
                        }
                    } catch (Exception eclose) {
                        LOG.error("initializePrefs-> lock", eclose);
                    }
                }
            }
            if (!ApplicationVersion.isOutOfDate(this)) {
                // Start the services now that everything is ready
                initializeServices(context);
            }
        }
    }
    configureDefaultBehavior(context);
    loadApplicationDictionaries(context);
}

From source file:JNLPAppletLauncher.java

/**
 * This method is called by the static initializer to create / initialize
 * the temp root directory that will hold the temp directories for this
 * instance of the JVM. This is done as follows:
 *
 *     1. Synchronize on a global lock. Note that for this purpose we will
 *        use System.out in the absence of a true global lock facility.
 *        We are careful not to hold this lock too long.
 *
 *     2. Check for the existence of the "jnlp.applet.launcher.tmproot"
 *        system property.//from   w  w w . j  a  v a  2s.c o  m
 *
 *         a. If set, then some other thread in a different ClassLoader has
 *            already created the tmprootdir, so we just need to
 *            use it. The remaining steps are skipped.
 *
 *         b. If not set, then we are the first thread in this JVM to run,
 *            and we need to create the the tmprootdir.
 *
 *     3. Create the tmprootdir, along with the appropriate locks.
 *        Note that we perform the operations in the following order,
 *        prior to creating tmprootdir itself, to work around the fact that
 *        the file creation and file lock steps are not atomic, and we need
 *        to ensure that a newly-created tmprootdir isn't reaped by a
 *        concurrently running JVM.
 *
 *            create jlnNNNN.tmp using File.createTempFile()
 *            lock jlnNNNN.tmp
 *            create jlnNNNN.lck while holding the lock on the .tmp file
 *            lock jlnNNNN.lck
 *
 *        Since the Reaper thread will enumerate the list of *.lck files
 *        before starting, we can guarantee that if there exists a *.lck file
 *        for an active process, then the corresponding *.tmp file is locked
 *        by that active process. This guarantee lets us avoid reaping an
 *        active process' files.
 *
 *     4. Set the "jnlp.applet.launcher.tmproot" system property.
 *
 *     5. Add a shutdown hook to cleanup jlnNNNN.lck and jlnNNNN.tmp. We
 *        don't actually expect that this shutdown hook will ever be called,
 *        but the act of doing this, ensures that the locks never get
 *        garbage-collected, which is necessary for correct behavior when
 *        the first ClassLoader is later unloaded, while subsequent Applets
 *        are still running.
 *
 *     6. Start the Reaper thread to cleanup old installations.
 */
private static void initTmpRoot() throws IOException {
    if (VERBOSE) {
        System.err.println("---------------------------------------------------");
    }

    synchronized (System.out) {

        // Get the name of the tmpbase directory.
        String tmpBaseName = System.getProperty("java.io.tmpdir") + File.separator + "jnlp-applet";
        tmpBaseDir = new File(tmpBaseName);

        // Get the value of the tmproot system property
        final String tmpRootPropName = "jnlp.applet.launcher.tmproot";

        tmpRootPropValue = System.getProperty(tmpRootPropName);

        if (tmpRootPropValue == null) {
            // Create the tmpbase directory if it doesn't already exist
            tmpBaseDir.mkdir();
            if (!tmpBaseDir.isDirectory()) {
                throw new IOException("Cannot create directory " + tmpBaseDir);
            }

            // Create ${tmpbase}/jlnNNNN.tmp then lock the file
            File tmpFile = File.createTempFile("jln", ".tmp", tmpBaseDir);
            if (VERBOSE) {
                System.err.println("tmpFile = " + tmpFile.getAbsolutePath());
            }
            final FileOutputStream tmpOut = new FileOutputStream(tmpFile);
            final FileChannel tmpChannel = tmpOut.getChannel();
            final FileLock tmpLock = tmpChannel.lock();

            // Strip off the ".tmp" to get the name of the tmprootdir
            String tmpFileName = tmpFile.getAbsolutePath();
            String tmpRootName = tmpFileName.substring(0, tmpFileName.lastIndexOf(".tmp"));

            // create ${tmpbase}/jlnNNNN.lck then lock the file
            String lckFileName = tmpRootName + ".lck";
            File lckFile = new File(lckFileName);
            if (VERBOSE) {
                System.err.println("lckFile = " + lckFile.getAbsolutePath());
            }
            lckFile.createNewFile();
            final FileOutputStream lckOut = new FileOutputStream(lckFile);
            final FileChannel lckChannel = lckOut.getChannel();
            final FileLock lckLock = lckChannel.lock();

            // Create tmprootdir
            tmpRootDir = new File(tmpRootName);
            if (DEBUG) {
                System.err.println("tmpRootDir = " + tmpRootDir.getAbsolutePath());
            }
            if (!tmpRootDir.mkdir()) {
                throw new IOException("Cannot create " + tmpRootDir);
            }

            // Add shutdown hook to cleanup the OutputStream, FileChannel,
            // and FileLock for the jlnNNNN.lck and jlnNNNN.lck files.
            // We do this so that the locks never get garbage-collected.
            Runtime.getRuntime().addShutdownHook(new Thread() {
                /* @Override */
                public void run() {
                    // NOTE: we don't really expect that this code will ever
                    // be called. If it does, we will close the output
                    // stream, which will in turn close the channel.
                    // We will then release the lock.
                    try {
                        tmpOut.close();
                        tmpLock.release();
                        lckOut.close();
                        lckLock.release();
                    } catch (IOException ex) {
                        // Do nothing
                    }
                }
            });

            // Set the system property...
            tmpRootPropValue = tmpRootName.substring(tmpRootName.lastIndexOf(File.separator) + 1);
            System.setProperty(tmpRootPropName, tmpRootPropValue);
            if (VERBOSE) {
                System.err.println("Setting " + tmpRootPropName + "=" + tmpRootPropValue);
            }

            // Start a new Reaper thread to do stuff...
            Thread reaperThread = new Thread() {
                /* @Override */
                public void run() {
                    deleteOldTempDirs();
                }
            };
            reaperThread.setName("AppletLauncher-Reaper");
            reaperThread.start();
        } else {
            // Make sure that the property is not set to an illegal value
            if (tmpRootPropValue.indexOf('/') >= 0 || tmpRootPropValue.indexOf(File.separatorChar) >= 0) {
                throw new IOException("Illegal value of: " + tmpRootPropName);
            }

            // Set tmpRootDir = ${tmpbase}/${jnlp.applet.launcher.tmproot}
            if (VERBOSE) {
                System.err.println("Using existing value of: " + tmpRootPropName + "=" + tmpRootPropValue);
            }
            tmpRootDir = new File(tmpBaseDir, tmpRootPropValue);
            if (DEBUG) {
                System.err.println("tmpRootDir = " + tmpRootDir.getAbsolutePath());
            }
            if (!tmpRootDir.isDirectory()) {
                throw new IOException("Cannot access " + tmpRootDir);
            }
        }
    }
}

From source file:org.panbox.core.crypto.io.EncRandomAccessFile.java

/**
 * tries to lock the underlying {@link RandomAccessFile}, if opened
 * //  w ww .  ja  v  a 2 s  .  c  o m
 * @param blocking
 * @return
 * @throws IOException
 */
public synchronized FileLock lock(boolean blocking) throws IOException {
    if (isOpen()) {
        FileChannel channel = backingRandomAccessFile.getChannel();
        FileLock ret;
        if (blocking) {
            ret = channel.lock();
        } else {
            ret = channel.tryLock();
        }

        return ret;
    } else {
        throw new IOException("Can't acquire lock for closed file!");
    }
}