Search in sources :

Example 81 with FileLock

use of java.nio.channels.FileLock in project chatty by chatty.

the class LogFile method tryFile.

/**
 * Tries to open the given file and obtain a lock on it. This may fail when
 * the file is already used by another process, or any other IOException of
 * course.
 *
 * @param file The file to attempt to open.
 * @return Returns true if the file is successfully opened and locked.
 */
private boolean tryFile(File file) {
    try {
        LOGGER.info("Log: Trying to open " + file.getAbsolutePath());
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.seek(raf.length());
        FileChannel channel = raf.getChannel();
        if (lockFile) {
            FileLock lock = channel.tryLock();
            if (lock != null) {
                writer = new BufferedWriter(Channels.newWriter(channel, CHARSET));
                valid = true;
                return true;
            }
        } else {
            writer = new BufferedWriter(Channels.newWriter(channel, CHARSET));
            valid = true;
            return true;
        }
    } catch (IOException ex) {
        LOGGER.warning("Log: Lock failed (" + file + " / " + ex + ")");
    }
    LOGGER.warning("Log: Lock failed (" + file + ")");
    return false;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter)

Example 82 with FileLock

use of java.nio.channels.FileLock in project tez by apache.

the class Fetcher method getLock.

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;
    }
    // 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;
}
Also used : Path(org.apache.hadoop.fs.Path) RandomAccessFile(java.io.RandomAccessFile) FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 83 with FileLock

use of java.nio.channels.FileLock in project activemq-artemis by apache.

the class LockAbstract method lockCLI.

void lockCLI(File lockPlace) throws Exception {
    if (lockPlace != null) {
        lockPlace.mkdirs();
        if (serverLockFile == null) {
            File fileLock = new File(lockPlace, "cli.lock");
            serverLockFile = new RandomAccessFile(fileLock, "rw");
        }
        try {
            FileLock lock = serverLockFile.getChannel().tryLock();
            if (lock == null) {
                throw new CLIException("Error: There is another process using the server at " + lockPlace + ". Cannot start the process!");
            }
            serverLockLock = lock;
        } catch (OverlappingFileLockException e) {
            throw new CLIException("Error: There is another process using the server at " + lockPlace + ". Cannot start the process!");
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileLock(java.nio.channels.FileLock) CLIException(org.apache.activemq.artemis.cli.CLIException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException)

Example 84 with FileLock

use of java.nio.channels.FileLock in project activemq-artemis by apache.

the class NIOSequentialFile method copyTo.

@Override
public void copyTo(SequentialFile dstFile) throws IOException {
    if (ActiveMQJournalLogger.LOGGER.isDebugEnabled()) {
        ActiveMQJournalLogger.LOGGER.debug("Copying " + this + " as " + dstFile);
    }
    if (isOpen()) {
        throw new IllegalStateException("File opened!");
    }
    if (dstFile.isOpen()) {
        throw new IllegalArgumentException("dstFile must be closed too");
    }
    try (RandomAccessFile src = new RandomAccessFile(getFile(), "rw");
        FileChannel srcChannel = src.getChannel();
        FileLock srcLock = srcChannel.lock()) {
        final long readableBytes = srcChannel.size();
        if (readableBytes > 0) {
            try (RandomAccessFile dst = new RandomAccessFile(dstFile.getJavaFile(), "rw");
                FileChannel dstChannel = dst.getChannel();
                FileLock dstLock = dstChannel.lock()) {
                final long oldLength = dst.length();
                final long newLength = oldLength + readableBytes;
                dst.setLength(newLength);
                final long transferred = dstChannel.transferFrom(srcChannel, oldLength, readableBytes);
                if (transferred != readableBytes) {
                    dstChannel.truncate(oldLength);
                    throw new IOException("copied less then expected");
                }
            }
        }
    }
}
Also used : ActiveMQIllegalStateException(org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException) RandomAccessFile(java.io.RandomAccessFile) FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException)

Example 85 with FileLock

use of java.nio.channels.FileLock in project cryptofs by cryptomator.

the class OpenCryptoFileTest method testTryLockDelegatesToChannel.

@Theory
public void testTryLockDelegatesToChannel(boolean shared) throws IOException {
    long position = 383872;
    long size = 48483;
    FileLock lock = mock(FileLock.class);
    when(channel.tryLock(position, size, shared)).thenReturn(lock);
    assertThat(inTest.tryLock(position, size, shared), is(lock));
}
Also used : FileLock(java.nio.channels.FileLock) Theory(org.junit.experimental.theories.Theory)

Aggregations

FileLock (java.nio.channels.FileLock)246 IOException (java.io.IOException)127 RandomAccessFile (java.io.RandomAccessFile)99 FileChannel (java.nio.channels.FileChannel)83 File (java.io.File)77 OverlappingFileLockException (java.nio.channels.OverlappingFileLockException)37 FileOutputStream (java.io.FileOutputStream)29 Test (org.junit.Test)19 Path (java.nio.file.Path)16 FileInputStream (java.io.FileInputStream)13 FileNotFoundException (java.io.FileNotFoundException)12 ByteBuffer (java.nio.ByteBuffer)10 InputStream (java.io.InputStream)5 Properties (java.util.Properties)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 NonWritableChannelException (java.nio.channels.NonWritableChannelException)4 NoSuchFileException (java.nio.file.NoSuchFileException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Map (java.util.Map)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3