Example usage for java.nio.channels FileLock isValid

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

Introduction

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

Prototype

public abstract boolean isValid();

Source Link

Document

Tells whether or not this lock is valid.

Usage

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 2  s  . c  o  m*/

        // 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:Main.java

public static void freeFileLock(FileLock fl, File file) {
    if (file != null) {
        file.delete();//  w w  w  . ja va2 s.  c  o  m
    }

    if (fl != null && fl.isValid()) {
        try {
            fl.release();
        } catch (IOException var3) {
            ;
        }

    }
}

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

public static Object lock(String lockfile) {
    RandomAccessFile raf = null;//  w ww .  j  av  a2s. c  o 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:edu.wustl.lookingglass.community.CommunityRepository.java

private void lockRepo() throws IOException {
    this.syncLockChannel = FileChannel.open(Paths.get(syncLockPath), StandardOpenOption.WRITE,
            StandardOpenOption.CREATE);
    FileLock lock = this.syncLockChannel.lock(); // gets an exclusive lock
    assert lock.isValid();
    this.syncLockChannel.write(ByteBuffer.wrap(ManagementFactory.getRuntimeMXBean().getName().getBytes()));
}

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

@Deprecated
public void releaseLocks() {
    l.trace("Trying to check file locks ");
    try {//  w w w.jav a  2s.  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:com.linkedin.helix.store.file.FilePropertyStore.java

@Override
public void updatePropertyUntilSucceed(String key, DataUpdater<T> updater, boolean createIfAbsent) {
    String path = getPath(key);//from ww  w  . j a  v a2  s .  co 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);/*  w  w w  . jav  a 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:org.apache.tez.runtime.library.common.shuffle.Fetcher.java

private void releaseLock(FileLock lock) throws IOException {
    if (lock != null && lock.isValid()) {
        FileChannel lockChannel = lock.channel();
        lock.release();/*from   w w w. j av  a 2 s. c  o m*/
        lockChannel.close();
    }
}

From source file:org.geoserver.platform.resource.FileLockProvider.java

public Resource.Lock acquire(final String lockKey) {
    // first off, synchronize among threads in the same jvm (the nio locks won't lock 
    // threads in the same JVM)
    final Resource.Lock memoryLock = memoryProvider.acquire(lockKey);

    // then synch up between different processes
    final File file = getFile(lockKey);
    try {/* ww  w .  j a v  a2 s  .c  o  m*/
        FileOutputStream currFos = null;
        FileLock currLock = null;
        try {
            // try to lock
            int count = 0;
            while (currLock == null && count < maxLockAttempts) {
                // the file output stream can also fail to be acquired due to the
                // other nodes deleting the file
                currFos = new FileOutputStream(file);
                try {
                    currLock = currFos.getChannel().lock();
                } catch (OverlappingFileLockException e) {
                    IOUtils.closeQuietly(currFos);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ie) {
                        // ok, moving on
                    }
                } catch (IOException e) {
                    // this one is also thrown with a message "avoided fs deadlock"
                    IOUtils.closeQuietly(currFos);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ie) {
                        // ok, moving on
                    }
                }
                count++;
            }

            // verify we managed to get the FS lock
            if (count >= maxLockAttempts) {
                throw new IllegalStateException(
                        "Failed to get a lock on key " + lockKey + " after " + count + " attempts");
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Lock " + lockKey + " acquired by thread " + Thread.currentThread().getId()
                        + " on file " + file);
            }

            // store the results in a final variable for the inner class to use
            final FileOutputStream fos = currFos;
            final FileLock lock = currLock;

            // nullify so that we don't close them, the locking occurred as expected
            currFos = null;
            currLock = null;

            return new Resource.Lock() {

                boolean released;

                public void release() {
                    if (released) {
                        return;
                    }

                    try {
                        released = true;
                        if (!lock.isValid()) {
                            // do not crap out, locks usage is only there to prevent duplication of work
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Lock key " + lockKey + " for releasing lock is unkonwn, it means "
                                        + "this lock was never acquired, or was released twice. "
                                        + "Current thread is: " + Thread.currentThread().getId() + ". "
                                        + "Are you running two instances in the same JVM using NIO locks? "
                                        + "This case is not supported and will generate exactly this error message");
                                return;
                            }
                        }
                        try {
                            lock.release();
                            IOUtils.closeQuietly(fos);
                            file.delete();

                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Lock " + lockKey + " released by thread "
                                        + Thread.currentThread().getId());
                            }
                        } catch (IOException e) {
                            throw new IllegalStateException(
                                    "Failure while trying to release lock for key " + lockKey, e);
                        }
                    } finally {
                        memoryLock.release();
                    }
                }

                @Override
                public String toString() {
                    return "FileLock " + file.getName();
                }
            };
        } finally {
            if (currLock != null) {
                currLock.release();
                memoryLock.release();
            }
            IOUtils.closeQuietly(currFos);
            file.delete();
        }
    } catch (IOException e) {
        throw new IllegalStateException("Failure while trying to get lock for key " + lockKey, e);
    }
}

From source file:org.geowebcache.locks.NIOLockProvider.java

public LockProvider.Lock getLock(final String lockKey) throws GeoWebCacheException {
    File file = null;//  www  .  j  ava  2s . c  om
    // first off, synchronize among threads in the same jvm (the nio locks won't lock 
    // threads in the same JVM)
    final LockProvider.Lock memoryLock = memoryProvider.getLock(lockKey);
    // then synch up between different processes
    try {
        file = getFile(lockKey);
        FileOutputStream currFos = null;
        FileLock currLock = null;
        try {
            // try to lock
            int count = 0;
            while (currLock == null && count < maxLockAttempts) {
                // the file output stream can also fail to be acquired due to the
                // other nodes deleting the file
                currFos = new FileOutputStream(file);
                try {
                    currLock = currFos.getChannel().lock();
                } catch (OverlappingFileLockException e) {
                    IOUtils.closeQuietly(currFos);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ie) {
                        // ok, moving on
                    }
                } catch (IOException e) {
                    // this one is also thrown with a message "avoided fs deadlock"
                    IOUtils.closeQuietly(currFos);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ie) {
                        // ok, moving on
                    }
                }
                count++;
            }

            // verify we managed to get the FS lock
            if (count >= maxLockAttempts) {
                throw new GeoWebCacheException(
                        "Failed to get a lock on key " + lockKey + " after " + count + " attempts");
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Lock " + lockKey + " acquired by thread " + Thread.currentThread().getId()
                        + " on file " + file);
            }

            // store the results in a final variable for the inner class to use
            final FileOutputStream fos = currFos;
            final FileLock lock = currLock;

            // nullify so that we don't close them, the locking occurred as expected
            currFos = null;
            currLock = null;

            final File lockFile = file;
            return new LockProvider.Lock() {

                boolean released;

                public void release() throws GeoWebCacheException {
                    if (released) {
                        return;
                    }

                    try {
                        released = true;
                        if (!lock.isValid()) {
                            // do not crap out, locks usage in GWC is only there to prevent duplication of work
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Lock key " + lockKey + " for releasing lock is unkonwn, it means "
                                        + "this lock was never acquired, or was released twice. "
                                        + "Current thread is: " + Thread.currentThread().getId() + ". "
                                        + "Are you running two GWC instances in the same JVM using NIO locks? "
                                        + "This case is not supported and will generate exactly this error message");
                                return;
                            }
                        }
                        try {
                            lock.release();
                            IOUtils.closeQuietly(fos);
                            lockFile.delete();

                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Lock " + lockKey + " released by thread "
                                        + Thread.currentThread().getId());
                            }
                        } catch (IOException e) {
                            throw new GeoWebCacheException(
                                    "Failure while trying to release lock for key " + lockKey, e);
                        }
                    } finally {
                        memoryLock.release();
                    }

                }
            };
        } finally {
            try {
                if (currLock != null) {
                    currLock.release();
                }
                IOUtils.closeQuietly(currFos);
                file.delete();
            } finally {
                memoryLock.release();
            }
        }
    } catch (IOException e) {
        throw new GeoWebCacheException("Failure while trying to get lock for key " + lockKey, e);
    }

}