Example usage for java.nio.channels FileChannel tryLock

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

Introduction

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

Prototype

public final FileLock tryLock() throws IOException 

Source Link

Document

Attempts to acquire an exclusive lock on this channel's file.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

    FileLock lock = channel.lock();

    lock = channel.tryLock();

    lock.release();//from ww  w.  ja va 2s  . c o m

    channel.close();
}

From source file:Lock.java

public static void main(String args[]) throws IOException, InterruptedException {
    RandomAccessFile file = null; // The file we'll lock
    FileChannel f = null; // The channel to the file
    FileLock lock = null; // The lock object we hold

    try { // The finally clause closes the channel and releases the lock
        // We use a temporary file as the lock file.
        String tmpdir = System.getProperty("java.io.tmpdir");
        String filename = Lock.class.getName() + ".lock";
        File lockfile = new File(tmpdir, filename);

        // Create a FileChannel that can read and write that file.
        // Note that we rely on the java.io package to open the file,
        // in read/write mode, and then just get a channel from it.
        // This will create the file if it doesn't exit. We'll arrange
        // for it to be deleted below, if we succeed in locking it.
        file = new RandomAccessFile(lockfile, "rw");
        f = file.getChannel();/* w w  w .j  a  v a  2s. c  om*/

        // Try to get an exclusive lock on the file.
        // This method will return a lock or null, but will not block.
        // See also FileChannel.lock() for a blocking variant.
        lock = f.tryLock();

        if (lock != null) {
            // We obtained the lock, so arrange to delete the file when
            // we're done, and then write the approximate time at which
            // we'll relinquish the lock into the file.
            lockfile.deleteOnExit(); // Just a temporary file

            // First, we need a buffer to hold the timestamp
            ByteBuffer bytes = ByteBuffer.allocate(8); // a long is 8 bytes

            // Put the time in the buffer and flip to prepare for writing
            // Note that many Buffer methods can be "chained" like this.
            bytes.putLong(System.currentTimeMillis() + 10000).flip();

            f.write(bytes); // Write the buffer contents to the channel
            f.force(false); // Force them out to the disk
        } else {
            // We didn't get the lock, which means another instance is
            // running. First, let the user know this.
            System.out.println("Another instance is already running");

            // Next, we attempt to read the file to figure out how much
            // longer the other instance will be running. Since we don't
            // have a lock, the read may fail or return inconsistent data.
            try {
                ByteBuffer bytes = ByteBuffer.allocate(8);
                f.read(bytes); // Read 8 bytes from the file
                bytes.flip(); // Flip buffer before extracting bytes
                long exittime = bytes.getLong(); // Read bytes as a long
                // Figure out how long that time is from now and round
                // it to the nearest second.
                long secs = (exittime - System.currentTimeMillis() + 500) / 1000;
                // And tell the user about it.
                System.out.println("Try again in about " + secs + " seconds");
            } catch (IOException e) {
                // This probably means that locking is enforced by the OS
                // and we were prevented from reading the file.
            }

            // This is an abnormal exit, so set an exit code.
            System.exit(1);
        }

        // Simulate a real application by sleeping for 10 seconds.
        System.out.println("Starting...");
        Thread.sleep(10000);
        System.out.println("Exiting.");
    } finally {
        // Always release the lock and close the file
        // Closing the RandomAccessFile also closes its FileChannel.
        if (lock != null && lock.isValid())
            lock.release();
        if (file != null)
            file.close();
    }
}

From source file:net.sf.jvifm.Main.java

public static boolean createFileLock() {
    File lockFile = new File(FilenameUtils.concat(HomeLocator.getConfigHome(), ".lock"));
    try {/*www .  j ava2s . c  o  m*/
        FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel();
        fileLock = channel.tryLock();
        if (fileLock != null) {
            return true;
        }
    } catch (Exception e) {
    }
    return false;
}

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 w ww . j  ava  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:gemlite.core.internal.support.system.WorkPathHelper.java

private static boolean lock(File directory) {
    String name = "node.lock";
    File lockfile = new File(directory, name);
    lockfile.deleteOnExit();// w  w  w.java 2 s . c o m
    try {
        FileChannel fc = (FileChannel) Channels.newChannel(new FileOutputStream(lockfile));
        lock = fc.tryLock();
        if (lock != null) {
            return true;
        }
    } catch (IOException x) {
        System.err.println(x.toString());
    } catch (OverlappingFileLockException e) {
        System.err.println(e.toString());
    }
    return false;
}

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

public static FileLock tryLock(File file) {
    FileLock toReturn = null;//w  w w . jav  a  2s.c o m

    try {
        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        try {
            FileChannel channel = raf.getChannel();
            toReturn = channel.tryLock();
            raf.writeBytes("lock file for: " + ManagementFactory.getRuntimeMXBean().getName());
        } finally {
            if (toReturn == null)
                raf.close();
        }
    } catch (OverlappingFileLockException e) {
        toReturn = null;
    } catch (FileNotFoundException e) {
        toReturn = null;
    } catch (IOException e) {
        toReturn = null;
    }

    return toReturn;
}

From source file:com.wabacus.util.FileLockTools.java

public static Object lock(String lockfile) {
    RandomAccessFile raf = null;/*from   w w w .  j  a v  a2s. co  m*/
    FileChannel fc = null;
    boolean islocked = true;
    try {
        raf = new RandomAccessFile(new File(lockfile), "rw");
        fc = raf.getChannel();
        FileLock fl = fc.tryLock();
        if (fl != null && fl.isValid()) {
            Map mapResources = new HashMap();
            mapResources.put("RAF", raf);
            mapResources.put("FC", fc);
            mapResources.put("FL", fl);
            return mapResources;
        } else {
            islocked = false;
            return null;
        }
    } catch (Exception e) {
        log.error("?" + lockfile + "?", e);
        return null;
    } finally {
        if (!islocked) {
            release(fc);
            release(raf);

        }
    }

}

From source file:com.all.login.LoginLock.java

public static final boolean getLock() {
    FileLock lock = null;/*from w  w  w. j av a  2s.  c  om*/
    try {
        File file = new File("allClientLock");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        for (int i = 0; i < 10 && lock == null; i++) {
            try {
                lock = channel.tryLock();
            } catch (Exception e) {
            }
            if (lock == null) {
                log.warn(
                        "All application is currently running unable to continue... try " + (i + 1) + " of 10");
            }
            Thread.sleep(1000);
        }
    } catch (Exception e) {
        return false;
    }
    return lock != null;
}

From source file:it.geosolutions.tools.io.file.IOUtils.java

/**
 * This method is responsible for checking if the input file is still being
 * written or if its available for being parsed.
 * //from  w  ww . j a  v a2  s  . co m
 * <p>
 * Specifically this method tries to open up a "rw" channel on the provided
 * input file. If the file is still being written this operation fails with
 * an exception, we therefore catch this exception and sleep for
 * {@value #ATOMIC_WAIT} seconds as defined in the constant
 * {@link #ATOMIC_WAIT}.
 * 
 * <p>
 * If after having waited for {@link MAX_WAITING_TIME_FOR_LOCK} (which is
 * read from the configuration or set to the default value of
 * {@link #DEFAULT_WAITING_TIME}) we have not yet acquired the channel we
 * skip this file but we signal this situation.
 * 
 * NOTE: To make use of mandatory locks, mandatory locking must be enabled
 * both on the file system that contains the file to be locked, and on the
 * file itself. Mandatory locking is enabled on a file system using the
 * "-o mand" option to mount(8), or the MS_MANDLOCK flag for mount(2).
 * Mandatory locking is enabled on a file by disabling group execute
 * permission on the file and enabling the set-group-ID permission bit (see
 * chmod(1) and chmod(2)).
 * 
 * @param caller
 * @param inputFile
 * @param maxwait
 * @return <code>true</code> if the lock has been successfully acquired.
 *         <code>false</code> otherwise
 * @throws InterruptedException
 * @throws IOException
 */
public static boolean acquireLock(Object caller, File inputFile, final long maxwait)
        throws InterruptedException, IOException {

    if (!inputFile.exists())
        return false;// file not exists!

    if (inputFile.isDirectory()) {
        // return inputFile.setReadOnly();
        return true;// cannot lock directory
    }

    // //
    //
    // Acquire an exclusive lock to wait for long
    // writing processes before trying to check on them
    //
    // //
    double sumWait = 0;
    while (true) {
        FileOutputStream outStream = null;
        FileChannel channel = null;
        FileLock lock = null;
        try {
            outStream = new FileOutputStream(inputFile, true);

            // get a rw channel
            channel = outStream.getChannel();
            if (channel != null) {
                // here we could block
                lock = channel.tryLock();
                if (lock != null) {
                    if (LOGGER.isTraceEnabled())
                        LOGGER.trace("File locked successfully");
                    return true;
                }
            }
        } catch (OverlappingFileLockException e) {
            // File is already locked in this thread or virtual machine
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("File is already locked in this thread or virtual machine");
        } catch (Exception e) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(e.getLocalizedMessage(), e);
        } finally {

            org.apache.commons.io.IOUtils.closeQuietly(outStream);

            // release the lock
            if (lock != null)
                try {
                    lock.release();
                } catch (Exception e) {
                    // eat me
                }

            if (channel != null)
                try {
                    channel.close();
                } catch (Exception e) {
                    // eat me
                }
        }

        // Sleep for ATOMIC_WAIT milliseconds prior to retry for acquiring
        // the lock
        synchronized (caller) {
            caller.wait(Conf.ATOMIC_WAIT);
        }

        sumWait += Conf.ATOMIC_WAIT;
        if (sumWait > maxwait) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn("Waiting time beyond maximum specified waiting time, exiting...");
            // Quitting the loop
            break;
        }
    }

    // A time greater than MAX_WAITING_TIME_FOR_LOCK has elapsed and no lock
    // has
    // been acquired. Thus, I need to return false
    return false;
}

From source file:org.chimi.s4s.fileservice.FileLockBasedThumbnailCreator.java

@Override
public File create(FileData fileData, Size newSize) throws IOException {
    String thumbnailPath = getThumbnailPath(fileData.getFileId(), newSize);
    File thumbnailFile = new File(thumbnailPath);
    if (thumbnailFile.exists()) {
        // ? ?? /*from w  w w.  j  a  v  a  2 s  .c o  m*/
        return thumbnailFile;
    }
    File lockFile = getLockFile(thumbnailPath);
    FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel();
    FileLock lock = null;
    try {
        lock = channel.tryLock();
    } catch (OverlappingFileLockException ex) {
    }

    if (lock == null) {
        // ??  , 1  ?? ?? ? ? 
        return createTemporaryThumbnail(thumbnailPath, fileData, newSize);
    }
    try {
        createThumbnail(thumbnailPath, fileData, newSize);
        return thumbnailFile;
    } finally {
        lock.release();
        channel.close();

        // TODO ? ?   
    }
}