Example usage for java.nio.channels FileLock release

List of usage examples for java.nio.channels FileLock release

Introduction

In this page you can find the example usage for java.nio.channels FileLock release.

Prototype

public abstract void release() throws IOException;

Source Link

Document

Releases this lock.

Usage

From source file:ee.ria.xroad.asyncdb.AsyncDBUtil.java

/**
 * Performs task under a lock which applies both to different operations and
 * different threads.//from   w ww  .j  av  a  2 s  .c o  m
 *
 * @param task - action to be performed
 * @param lockFilePath - path to file used for process locking
 * @param lockable - object to be synchronized between threads
 * @param <T> - type of result
 * @return - object returned as a result of operation
 * @throws Exception - when locked operation fails or cannot be performed
 */
public static <T> T performLocked(Callable<T> task, String lockFilePath, Object lockable) throws Exception {
    try (RandomAccessFile raf = new RandomAccessFile(lockFilePath, "rw");
            FileOutputStream fos = new FileOutputStream(raf.getFD())) {
        synchronized (lockable) {
            FileLock lock = fos.getChannel().lock();
            try {
                return task.call();
            } finally {
                lock.release();
            }
        }
    }
}

From source file:com.github.neoio.nio.util.NIOUtils.java

public static void releaseFileLock(FileLock lock) throws NetIOException {
    try {//www  .j a v a 2s .c o  m
        lock.release();
    } catch (IOException e) {
        throw new NetIOException(e);
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.PeriodicResourceUpdater.java

static void copyDatabase(final File existingDB, final File newDB) throws IOException {
    final FileInputStream in = new FileInputStream(newDB);
    final FileOutputStream out = new FileOutputStream(existingDB);
    final FileLock lock = out.getChannel().tryLock();
    if (lock != null) {
        LOGGER.info("Updating location database.");
        IOUtils.copy(in, out);/*from  w  ww .  j a  v  a  2s .c  o  m*/
        existingDB.setReadable(true, false);
        existingDB.setWritable(true, false);
        lock.release();
        LOGGER.info("Successfully updated location database.");
    } else {
        LOGGER.info("Location database locked by another process.");
    }
    IOUtils.closeQuietly(in);
    IOUtils.closeQuietly(out);
}

From source file:com.notifier.desktop.Main.java

private static boolean getExclusiveExecutionLock() throws IOException {
    File lockFile = new File(OperatingSystems.getWorkDirectory(), Application.ARTIFACT_ID + ".lock");
    Files.createParentDirs(lockFile);
    lockFile.createNewFile();/*from   www . j  a  v  a 2  s .  c  o m*/
    final RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile, "rw");
    final FileChannel fileChannel = randomAccessFile.getChannel();
    final FileLock fileLock = fileChannel.tryLock();
    if (fileLock == null) {
        Closeables.closeQuietly(fileChannel);
        Closeables.closeQuietly(randomAccessFile);
        return false;
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                fileLock.release();
            } catch (IOException e) {
                System.err.println("Error releasing file lock");
                e.printStackTrace(System.err);
            } finally {
                Closeables.closeQuietly(fileChannel);
                Closeables.closeQuietly(randomAccessFile);
            }
        }
    });
    return true;
}

From source file:ubicrypt.core.Utils.java

private static void close(final InputStream is, final FileLock lock) {
    try {//from  w  w w .j a v a  2  s  .  com
        lock.release();
    } catch (final IOException e) {
    }
    try {
        is.close();
    } catch (final IOException e1) {

    }
}

From source file:ch.admin.suis.msghandler.util.FileUtils.java

/**
 * Returns//from   ww  w  .j  av  a  2s  .c  om
 * <code>true</code>, if the given file can be read by the application. This methods tries to acquire a shared lock
 * over the specified file. This lock is then immediately released. if an error occurs while acuiring the lock, this
 * method returns
 * <code>false</code>.
 *
 * @param pathname The path to the file
 * @return boolean. True if the file can be read, false otherwise.
 */
public static boolean canRead(File pathname) {
    if (!pathname.canRead()) {
        return false;
    }

    try (FileInputStream fis = new FileInputStream(pathname)) {
        FileLock lock = fis.getChannel().tryLock(0, Long.MAX_VALUE, true);

        if (lock != null) {
            // do not hold the lock
            lock.release();

            return true;
        } else {
            LOG.info("cannot lock the file " + pathname.getAbsolutePath()
                    + "; it is probably locked by another application");
            return false;
        }
    } catch (IOException e) {
        LOG.error("an exception occured while trying to acquire lock on the file " + pathname.getAbsolutePath(),
                e);
        return false;
    }
}

From source file:org.opencastproject.util.IoSupport.java

private static Effect0 aquireLock(File file) {
    try {//from  www  . ja v a  2s .com
        final RandomAccessFile raf = new RandomAccessFile(file, "rw");
        final FileLock lock = raf.getChannel().lock();
        return new Effect0() {
            @Override
            protected void run() {
                try {
                    lock.release();
                } catch (IOException ignore) {
                }
                IoSupport.closeQuietly(raf);
            }
        };
    } catch (Exception e) {
        throw new RuntimeException("Error aquiring lock for " + file.getAbsolutePath(), e);
    }
}

From source file:org.apache.nifi.file.FileUtils.java

/**
 * Releases the given lock quietly - no logging, no exception
 *
 * @param lock/*from ww  w . j a va 2s. co m*/
 */
public static void releaseQuietly(final FileLock lock) {
    if (null != lock) {
        try {
            lock.release();
        } catch (final IOException io) {
            /*IGNORE*/
        }
    }
}

From source file:org.ngrinder.common.util.FileUtil.java

/**
 * Write object into file.//from  w  w  w  .ja  v  a 2s .c om
 * 
 * @param file
 *            file
 * @param obj
 *            obj to be written.
 */
public static void writeObjectToFile(File file, Object obj) {
    FileOutputStream fout = null;
    ObjectOutputStream oout = null;
    ByteArrayOutputStream bout = null;
    FileLock lock = null;
    try {
        bout = new ByteArrayOutputStream();
        oout = new ObjectOutputStream(bout);
        oout.writeObject(obj);
        oout.flush();
        byte[] byteArray = bout.toByteArray();
        fout = new FileOutputStream(file, false);
        lock = fout.getChannel().lock();
        fout.write(byteArray);
    } catch (Exception e) {
        LOGGER.error("IO error for file {} : {}", file, e.getMessage());
        LOGGER.debug("Details : ", e);
    } finally {
        if (lock != null) {
            try {
                lock.release();
            } catch (Exception e) {
                LOGGER.error("unlocking is failed for file {}", file, e);
            }
        }
        IOUtils.closeQuietly(bout);
        IOUtils.closeQuietly(fout);
        IOUtils.closeQuietly(oout);
    }
}

From source file:storybook.SbApp.java

private static boolean lockInstance(final String lockFile) {
    try {/*  www  .j  av  a  2  s  .  co m*/
        final File file = new File(lockFile);
        final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        final FileLock fileLock = randomAccessFile.getChannel().tryLock();
        if (fileLock != null) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    try {
                        fileLock.release();
                        randomAccessFile.close();
                        file.delete();
                    } catch (IOException e) {
                        System.err.println("Unable to remove lock file: " + lockFile + "->" + e.getMessage());
                    }
                }
            });
            return true;
        }
    } catch (IOException e) {
        System.err.println("Unable to create and/or lock file: " + lockFile + "->" + e.getMessage());
    }
    return false;
}