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 abstract FileLock tryLock(long position, long size, boolean shared) throws IOException;

Source Link

Document

Attempts to acquire a lock on the given region of 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(0, Long.MAX_VALUE, true);

    lock = channel.tryLock(0, Long.MAX_VALUE, true);

    boolean isShared = lock.isShared();

    lock.release();/*from w w  w.  j a v a2  s  .c o  m*/

    channel.close();
}

From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java

/**
 * Obtains a file lock on the repository lock file.
 *///from  w ww  . ja  v  a2 s  .c  om
protected RepositoryFileLock obtainRepositoryFileLock(final boolean shared, final int timeout)
        throws IOException {
    Log logger = this.getLog();

    if (logger.isDebugEnabled())
        logger.debug("Obtaining repository file lock (shared: " + shared + ").");

    RepositoryFileLock repositoryFileLock = null;
    FileLock lock = null;
    final long beginWait = System.currentTimeMillis();

    while (repositoryFileLock == null) {
        try {
            RandomAccessFile lockFile = new RandomAccessFile(
                    new File(moduleRepositoryDirectory, LOCK_FILE_NAME), "rws");
            FileChannel channel = lockFile.getChannel();

            // Attempt to obtain a lock on the file
            lock = channel.tryLock(0L, Long.MAX_VALUE, shared);
            if (!shared && (lockFile.length() == 0)) {
                lockFile.write(new String("LOCK").getBytes());
                lockFile.getFD().sync();
            }
            repositoryFileLock = new RepositoryFileLock(lockFile, lock);
        } catch (IOException ioe) {
            if (logger.isDebugEnabled())
                logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ioe);
            if (timeout < 0)
                throw ioe;
        } catch (OverlappingFileLockException ofle) {
            if (logger.isDebugEnabled())
                logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ofle);
            if (timeout < 0)
                throw ofle;
        }

        if (repositoryFileLock == null) // This statement shouldn't be reaced if timeout is < 0
        {
            if ((System.currentTimeMillis() - beginWait) > timeout) // Wait a maximum of timeout milliseconds on lock
            {
                throw new IOException("Timeout while waiting for file lock on repository lock file!");
            } else {
                // Otherwise - wait a while before trying to obtain a lock again
                try {
                    Thread.sleep(Math.min(250, timeout - (System.currentTimeMillis() - beginWait)));
                } catch (InterruptedException ie) {
                }
            }
        }
    }

    if (logger.isDebugEnabled())
        logger.debug("Repository file lock (shared: " + shared + ") obtained.");

    return repositoryFileLock;
}

From source file:com.edgenius.wiki.service.impl.SitemapServiceImpl.java

private void appendSitemapIndex(String sitemap) throws IOException {
    File sitemapIndexFile = new File(mapResourcesRoot.getFile(), SITEMAP_INDEX_NAME);
    if (!sitemapIndexFile.exists()) {
        //if a new sitemap file
        List<String> lines = new ArrayList<String>();
        lines.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        lines.add("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
        lines.add("</sitemapindex>");
        FileUtils.writeLines(sitemapIndexFile, lines);
    }//from w  w w  .  j  av a 2 s. com

    RandomAccessFile rfile = new RandomAccessFile(sitemapIndexFile, "rw");
    FileChannel channel = rfile.getChannel();

    //this new content will append to end of file before XML end tag
    StringBuilder lines = new StringBuilder();
    lines.append("   <sitemap>\n");
    lines.append("     <loc>" + WebUtil.getHostAppURL() + SITEMAP_URL_CONTEXT + sitemap + "</loc>\n");
    lines.append("     <lastmod>" + TIME_FORMAT.format(new Date()) + " </lastmod>\n");
    lines.append("   </sitemap>\n");
    //the last tag will be overwrite, so append it again to new content. 
    lines.append(SITEMAP_INDEX_TAIL_FLAG);
    byte[] content = lines.toString().getBytes();

    ByteBuffer byteBuf = ByteBuffer.allocate(512);
    // seek first
    int len = 0, headIdx = 0;
    long tailIdx = channel.size() - 512;
    tailIdx = tailIdx < 0 ? 0 : tailIdx;

    long headPos = -1;
    StringBuilder header = new StringBuilder();
    while ((len = channel.read(byteBuf, tailIdx)) > 0) {
        byteBuf.rewind();
        byte[] dst = new byte[len];
        byteBuf.get(dst, 0, len);
        header.append(new String(dst, "UTF8"));
        headIdx = header.indexOf(SITEMAP_INDEX_TAIL_FLAG);
        if (headIdx != -1) {
            headPos = channel.size() - header.substring(headIdx).getBytes().length;
            break;
        }
    }
    FileLock lock = channel.tryLock(headPos, content.length, false);
    try {
        channel.write(ByteBuffer.wrap(content), headPos);
    } finally {
        lock.release();
    }

    channel.force(false);
    rfile.close();

}

From source file:MyZone.Settings.java

public byte[] readXML(String filename) {
    byte[] readIn = null;
    FileChannel channel = null;
    FileLock lock = null;// ww  w.  j  av  a  2  s .c  o m
    FileInputStream fis = null;
    ByteArrayOutputStream baos = null;
    try {
        File file = new File(filename);
        if (!file.exists()) {
            return null;
        }
        fis = new FileInputStream(file);
        channel = fis.getChannel();
        while ((lock = channel.tryLock(0L, Long.MAX_VALUE, true)) == null) {
            Thread.yield();
        }
        baos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        ByteBuffer buf = ByteBuffer.wrap(b);
        int count = 0;
        long fileLength = file.length();
        while (fileLength > 0) {
            count = channel.read(buf);
            if (count >= 0) {
                fileLength -= count;
                baos.write(b, 0, count);
                buf.rewind();
            }
        }
        readIn = baos.toByteArray();
    } catch (Exception e) {
        if (DEBUG) {
            e.printStackTrace();
        }
        readIn = null;
    } finally {
        try {
            if (lock != null) {
                lock.release();
            }
            if (channel != null) {
                channel.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (baos != null) {
                baos.close();
            }
        } catch (Exception e) {
            if (DEBUG) {
                e.printStackTrace();
            }
            readIn = null;
        }
    }
    return readIn;
}

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

public static long copyBytes(final byte[] bytes, final File destination, final boolean lockOutputFile)
        throws FileNotFoundException, IOException {
    FileOutputStream fos = null;//  ww w .ja v a2 s  . c  om
    FileLock outLock = null;
    long fileSize = 0L;
    try {
        fos = new FileOutputStream(destination);
        final FileChannel out = fos.getChannel();
        if (lockOutputFile) {
            outLock = out.tryLock(0, Long.MAX_VALUE, false);
            if (null == outLock) {
                throw new IOException(
                        "Unable to obtain exclusive file lock for: " + destination.getAbsolutePath());
            }
        }
        fos.write(bytes);
        fos.flush();
        fileSize = bytes.length;
    } finally {
        FileUtils.releaseQuietly(outLock);
        FileUtils.closeQuietly(fos);
    }
    return fileSize;
}

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

/**
 * Copies the given source file to the given destination file. The given
 * destination will be overwritten if it already exists.
 *
 * @param source/*  ww w.ja va  2  s.  c om*/
 * @param destination
 * @param lockInputFile if true will lock input file during copy; if false
 * will not
 * @param lockOutputFile if true will lock output file during copy; if false
 * will not
 * @param move if true will perform what is effectively a move operation
 * rather than a pure copy. This allows for potentially highly efficient
 * movement of the file but if not possible this will revert to a copy then
 * delete behavior. If false, then the file is copied and the source file is
 * retained. If a true rename/move occurs then no lock is held during that
 * time.
 * @param logger if failures occur, they will be logged to this logger if
 * possible. If this logger is null, an IOException will instead be thrown,
 * indicating the problem.
 * @return long number of bytes copied
 * @throws FileNotFoundException if the source file could not be found
 * @throws IOException
 * @throws SecurityException if a security manager denies the needed file
 * operations
 */
public static long copyFile(final File source, final File destination, final boolean lockInputFile,
        final boolean lockOutputFile, final boolean move, final Logger logger)
        throws FileNotFoundException, IOException {

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileLock inLock = null;
    FileLock outLock = null;
    long fileSize = 0L;
    if (!source.canRead()) {
        throw new IOException("Must at least have read permission");

    }
    if (move && source.renameTo(destination)) {
        fileSize = destination.length();
    } else {
        try {
            fis = new FileInputStream(source);
            fos = new FileOutputStream(destination);
            final FileChannel in = fis.getChannel();
            final FileChannel out = fos.getChannel();
            if (lockInputFile) {
                inLock = in.tryLock(0, Long.MAX_VALUE, true);
                if (null == inLock) {
                    throw new IOException("Unable to obtain shared file lock for: " + source.getAbsolutePath());
                }
            }
            if (lockOutputFile) {
                outLock = out.tryLock(0, Long.MAX_VALUE, false);
                if (null == outLock) {
                    throw new IOException(
                            "Unable to obtain exclusive file lock for: " + destination.getAbsolutePath());
                }
            }
            long bytesWritten = 0;
            do {
                bytesWritten += out.transferFrom(in, bytesWritten, TRANSFER_CHUNK_SIZE_BYTES);
                fileSize = in.size();
            } while (bytesWritten < fileSize);
            out.force(false);
            FileUtils.closeQuietly(fos);
            FileUtils.closeQuietly(fis);
            fos = null;
            fis = null;
            if (move && !FileUtils.deleteFile(source, null, 5)) {
                if (logger == null) {
                    FileUtils.deleteFile(destination, null, 5);
                    throw new IOException("Could not remove file " + source.getAbsolutePath());
                } else {
                    logger.warn(
                            "Configured to delete source file when renaming/move not successful.  However, unable to delete file at: "
                                    + source.getAbsolutePath());
                }
            }
        } finally {
            FileUtils.releaseQuietly(inLock);
            FileUtils.releaseQuietly(outLock);
            FileUtils.closeQuietly(fos);
            FileUtils.closeQuietly(fis);
        }
    }
    return fileSize;
}

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

public static long copyFile(final File source, final OutputStream stream, final boolean closeOutputStream,
        final boolean lockInputFile) throws FileNotFoundException, IOException {
    FileInputStream fis = null;/* ww  w.  jav a 2 s  .  com*/
    FileLock inLock = null;
    long fileSize = 0L;
    try {
        fis = new FileInputStream(source);
        final FileChannel in = fis.getChannel();
        if (lockInputFile) {
            inLock = in.tryLock(0, Long.MAX_VALUE, true);
            if (inLock == null) {
                throw new IOException("Unable to obtain exclusive file lock for: " + source.getAbsolutePath());
            }

        }

        byte[] buffer = new byte[1 << 18]; //256 KB
        int bytesRead = -1;
        while ((bytesRead = fis.read(buffer)) != -1) {
            stream.write(buffer, 0, bytesRead);
        }
        in.force(false);
        stream.flush();
        fileSize = in.size();
    } finally {
        FileUtils.releaseQuietly(inLock);
        FileUtils.closeQuietly(fis);
        if (closeOutputStream) {
            FileUtils.closeQuietly(stream);
        }
    }
    return fileSize;
}

From source file:org.apache.tez.runtime.library.common.shuffle.Fetcher.java

private FileLock getLock() throws OverlappingFileLockException, InterruptedException, IOException {
    File lockFile = localFs.pathToFile(new Path(lockPath, host + ".lock"));

    final boolean created = lockFile.createNewFile();

    if (created == false && !lockFile.exists()) {
        // bail-out cleanly
        return null;
    }// w ww .  ja v  a  2 s. c o  m

    // invariant - file created (winner writes to this file)
    // caveat: closing lockChannel does close the file (do not double close)
    // JDK7 - TODO: use AsynchronousFileChannel instead of RandomAccessFile
    FileChannel lockChannel = new RandomAccessFile(lockFile, "rws").getChannel();
    FileLock xlock = null;

    xlock = lockChannel.tryLock(0, Long.MAX_VALUE, false);
    if (xlock != null) {
        return xlock;
    }
    lockChannel.close();
    return null;
}