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:org.apache.flume.channel.file.Log.java

/**
 * 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 exculsive access to the
 * storage directory. Otherwise, no guarantee is given.
 *
 * @throws IOException if locking fails// w w  w . jav  a 2s. c o m
 */
private void lock(File dir) throws IOException {
    FileLock lock = tryLock(dir);
    if (lock == null) {
        String msg = "Cannot lock " + dir + ". The directory is already locked. " + channelNameDescriptor;
        LOGGER.info(msg);
        throw new IOException(msg);
    }
    FileLock secondLock = tryLock(dir);
    if (secondLock != null) {
        LOGGER.warn("Directory " + dir + " does not support locking");
        secondLock.release();
        secondLock.channel().close();
    }
    locks.put(dir.getAbsolutePath(), lock);
}

From source file:org.apache.hadoop.hdfs.server.common.Storage.java

/**
 * Check whether underlying file system supports file locking.
 * /*from w w w. java2s.  c  o m*/
 * @return <code>true</code> if exclusive locks are supported or
 *         <code>false</code> otherwise.
 * @throws IOException
 * @see StorageDirectory#lock()
 */
public boolean isLockSupported(int idx) throws IOException {
    StorageDirectory sd = storageDirs.get(idx);
    FileLock firstLock = null;
    FileLock secondLock = null;
    try {
        firstLock = sd.lock;
        if (firstLock == null) {
            firstLock = sd.tryLock();
            if (firstLock == null)
                return true;
        }
        secondLock = sd.tryLock();
        if (secondLock == null)
            return true;
    } finally {
        if (firstLock != null && firstLock != sd.lock) {
            firstLock.release();
            firstLock.channel().close();
        }
        if (secondLock != null) {
            secondLock.release();
            secondLock.channel().close();
        }
    }
    return false;
}

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();
        lockChannel.close();//from www . jav  a 2 s.  c om
    }
}

From source file:com.att.api.oauth.OAuthToken.java

/**
 * Saves this token to a file in an asynchronous-safe manner.
 *
 * @param fpath file path/*from  w ww  .j a  v  a 2s.c  om*/
 * @throws IOException if unable to save token
 */
public void saveToken(String fpath) throws IOException {
    FileOutputStream fOutputStream = null;
    FileLock fLock = null;

    // save to cached tokens
    synchronized (LOCK_OBJECT) {
        // lazy init
        if (cachedTokens == null) {
            cachedTokens = new HashMap<String, OAuthToken>();
        }
        OAuthToken.cachedTokens.put(fpath, this);

        try {
            fOutputStream = new FileOutputStream(fpath);
            fLock = fOutputStream.getChannel().lock();
            Properties props = new Properties();
            props.setProperty("accessToken", accessToken);
            props.setProperty("creationTime", String.valueOf(creationTime));
            props.setProperty("expiresIn", String.valueOf(expiresIn));
            props.setProperty("refreshToken", refreshToken);
            props.store(fOutputStream, "Token Information");
        } catch (IOException e) {
            throw e; // pass along exception
        } finally {
            if (fLock != null) {
                fLock.release();
            }
            if (fOutputStream != null) {
                fOutputStream.close();
            }
        }
    }
}

From source file:org.spf4j.perf.tsdb.TimeSeriesDatabase.java

public TimeSeriesDatabase(final String pathToDatabaseFile, final boolean isWrite, final byte... metaData)
        throws IOException {
    file = new RandomAccessFile(pathToDatabaseFile, isWrite ? "rw" : "r");
    // uniques per process string for sync purposes.
    this.path = INTERNER.intern(new File(pathToDatabaseFile).getPath());
    tables = new ConcurrentHashMap<>();
    writeDataFragments = new HashMap<>();
    // read or create header
    synchronized (path) {
        this.ch = file.getChannel();
        FileLock lock;
        if (isWrite) {
            lock = ch.lock();/*from ww w. ja  v  a  2  s  .co  m*/
        } else {
            lock = ch.lock(0, Long.MAX_VALUE, true);
        }
        try {
            if (file.length() == 0) {
                this.header = new Header(VERSION, metaData);
                this.header.writeTo(file);
                this.toc = new TableOfContents(file.getFilePointer());
                this.toc.writeTo(file);
            } else {
                this.header = new Header(file);
                this.toc = new TableOfContents(file);
            }
        } catch (IOException | RuntimeException e) {
            try {
                lock.release();
                throw e;
            } catch (IOException ex) {
                ex.addSuppressed(e);
                throw ex;
            }
        }
        lock.release();
        lock = ch.lock(0, Long.MAX_VALUE, true);
        try {
            readTableInfos();
        } catch (IOException | RuntimeException e) {
            try {
                lock.release();
                throw e;
            } catch (IOException ex) {
                ex.addSuppressed(e);
                throw ex;
            }
        }
        lock.release();
    }
}

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  w  ww  . j  a v a  2s. 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:org.apache.synapse.config.xml.MultiXMLConfigurationSerializer.java

private boolean isWritable(File file) {
    if (file.isDirectory()) {
        // Further generalize this check
        if (".svn".equals(file.getName())) {
            return true;
        }// w w w . j av  a 2 s . co m

        File[] children = file.listFiles();
        for (File child : children) {
            if (!isWritable(child)) {
                log.warn("File: " + child.getName() + " is not writable");
                return false;
            }
        }

        if (!file.canWrite()) {
            log.warn("Directory: " + file.getName() + " is not writable");
            return false;
        }
        return true;

    } else {
        if (!file.canWrite()) {
            log.warn("File: " + file.getName() + " is not writable");
            return false;
        }

        FileOutputStream fos = null;
        FileLock lock = null;
        boolean writable;

        try {
            fos = new FileOutputStream(file, true);
            FileChannel channel = fos.getChannel();
            lock = channel.tryLock();
        } catch (IOException e) {
            log.warn("Error while attempting to lock the file: " + file.getName(), e);
            writable = false;
        } finally {
            if (lock != null) {
                writable = true;
                try {
                    lock.release();
                } catch (IOException e) {
                    log.warn("Error while releasing the lock on file: " + file.getName(), e);
                    writable = false;
                }
            } else {
                log.warn("Unable to acquire lock on file: " + file.getName());
                writable = false;
            }

            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.warn("Error while closing the stream on file: " + file.getName(), e);
                writable = false;
            }
        }
        return writable;
    }
}

From source file:com.taobao.common.tfs.impl.GcWorker.java

private void doGc(SegmentInfoContainer segmentInfoContainer, File[] fileList) {
    for (File file : fileList) {
        if (file.length() == 0) {
            log.info("expired gc file is empty, unlink. " + file.getAbsolutePath());
            file.delete();//from w w w. ja va  2s .  co  m
            continue;
        }

        String fileName = file.getAbsolutePath();
        log.info("do gc filename " + fileName);

        int serverIdIndex = fileName.lastIndexOf('!');
        if (serverIdIndex == -1) {
            log.error("file name is invalid, no server id: " + fileName);
            // unlink ?
            continue;
        }

        FileLock fileLock = null;
        try {
            FileChannel fileChannel = (new RandomAccessFile(file, "rw")).getChannel();
            fileLock = fileChannel.tryLock();
            if (fileLock == null) {
                log.warn("file: " + fileName + " is busy, maybe another gc worker is working over it");
                continue;
            }

            long serverId = Long.parseLong(fileName.substring(serverIdIndex + 1));
            segmentInfoContainer.loadFile(fileName);
            Collection<SegmentInfo> segmentInfos = segmentInfoContainer.getSegmentInfos();

            for (SegmentInfo segmentInfo : segmentInfos) {
                if (tfsManager.unlinkFile(segmentInfo.getBlockId(), segmentInfo.getFileId(), serverId)) {
                    log.info("gc success. blockId: " + segmentInfo.getBlockId() + " fileId: "
                            + segmentInfo.getFileId() + " serverId: " + serverId);
                } else {
                    log.error("gc fail. blockId: " + segmentInfo.getFileId() + " fileId: "
                            + segmentInfo.getFileId() + " serverId: " + serverId);
                }
            }
        } catch (Exception e) {
            log.warn("", e);
        } finally {
            try {
                if (fileLock != null) {
                    fileLock.release();
                }
                segmentInfoContainer.cleanUp();
                // delete anyway
                file.delete();
            } catch (Exception e) {
                log.warn("filelock realse fail.", e);
            }
        }
    }
}

From source file:org.spf4j.perf.tsdb.TimeSeriesDatabase.java

public void addTSTable(final String tableName, final byte[] tableMetaData, final int sampleTime,
        final String[] columnNames, final byte[][] columnMetaData) throws IOException {
    synchronized (path) {
        if (hasTSTable(tableName)) {
            throw new IllegalArgumentException("group already exists " + tableName);
        }//from   ww w. j  a  va 2 s.  c  o m
        flush();
        FileLock lock = ch.lock();
        TSTable colInfo;
        try {
            readLastTableInfo();
            //write column information at the end of the file.
            file.seek(file.length());
            colInfo = new TSTable(tableName, tableMetaData, columnNames, columnMetaData, sampleTime,
                    file.getFilePointer());
            colInfo.writeTo(file);
            //update refferences to this new TableInfo.
            if (lastTableInfo != null) {
                lastTableInfo.setNextColumnInfo(colInfo.getLocation(), file);
            } else {
                toc.setFirstTableInfo(colInfo.getLocation(), file);
            }
            toc.setLastTableInfo(colInfo.getLocation(), file);
        } catch (IOException | RuntimeException e) {
            try {
                lock.release();
                throw e;
            } catch (IOException ex) {
                ex.addSuppressed(e);
                throw ex;
            }
        }
        lock.release();

        lastTableInfo = colInfo;
        tables.put(tableName, colInfo);
    }
}

From source file:org.mule.transport.file.FileMessageReceiver.java

/**
 * Try to acquire a lock on a file and release it immediately. Usually used as a
 * quick check to see if another process is still holding onto the file, e.g. a
 * large file (more than 100MB) is still being written to.
 *
 * @param sourceFile file to check//from   w  w w .j  av a 2s  .  co m
 * @return <code>true</code> if the file can be locked
 */
protected boolean attemptFileLock(final File sourceFile) throws MuleException {
    // check if the file can be processed, be sure that it's not still being
    // written
    // if the file can't be locked don't process it yet, since creating
    // a new FileInputStream() will throw an exception
    FileLock lock = null;
    FileChannel channel = null;
    boolean fileCanBeLocked = false;
    try {
        channel = new RandomAccessFile(sourceFile, "rw").getChannel();

        // Try acquiring the lock without blocking. This method returns
        // null or throws an exception if the file is already locked.
        lock = channel.tryLock();
    } catch (FileNotFoundException fnfe) {
        throw new DefaultMuleException(FileMessages.fileDoesNotExist(sourceFile.getName()));
    } catch (IOException e) {
        // Unable to create a lock. This exception should only be thrown when
        // the file is already locked. No sense in repeating the message over
        // and over.
    } finally {
        if (lock != null) {
            // if lock is null the file is locked by another process
            fileCanBeLocked = true;
            try {
                // Release the lock
                lock.release();
            } catch (IOException e) {
                // ignore
            }
        }

        if (channel != null) {
            try {
                // Close the file
                channel.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return fileCanBeLocked;
}