Search in sources :

Example 96 with FileLock

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

the class SingleFilePageSwapperTest method creatingSwapperForInternallyLockedFileMustThrow.

@Test
@DisabledOnOs(OS.WINDOWS)
void creatingSwapperForInternallyLockedFileMustThrow() throws Exception {
    PageSwapperFactory factory = createSwapperFactory(fileSystem);
    Path file = testDir.file("file");
    StoreFileChannel channel = fileSystem.write(file);
    try (FileLock fileLock = channel.tryLock()) {
        assertThat(fileLock).isNotNull();
        assertThrows(FileLockException.class, () -> createSwapper(factory, file, 4, NO_CALLBACK, true));
    }
}
Also used : Path(java.nio.file.Path) PageSwapperFactory(org.neo4j.io.pagecache.PageSwapperFactory) StoreFileChannel(org.neo4j.io.fs.StoreFileChannel) FileLock(java.nio.channels.FileLock) DisabledOnOs(org.junit.jupiter.api.condition.DisabledOnOs) PageSwapperTest(org.neo4j.io.pagecache.PageSwapperTest) Test(org.junit.jupiter.api.Test)

Example 97 with FileLock

use of java.nio.channels.FileLock in project atlas by alibaba.

the class MultiDexExtractor method load.

/**
 * Extracts application secondary dexes into files in the application data
 * directory.
 *
 * @return a list of files that were created. The list may be empty if there
 *         are no secondary dex files. Never return null.
 * @throws IOException if encounters a problem while reading or writing
 *         secondary dex files
 */
static List<? extends File> load(Context context, File sourceApk, File dexDir, String prefsKeyPrefix, boolean forceReload) throws IOException {
    Log.i(TAG, "MultiDexExtractor.load(" + sourceApk.getPath() + ", " + forceReload + ", " + prefsKeyPrefix + ")");
    long currentCrc = getZipCrc(sourceApk);
    // Validity check and extraction must be done only while the lock file has been taken.
    File lockFile = new File(dexDir, LOCK_FILENAME);
    RandomAccessFile lockRaf = new RandomAccessFile(lockFile, "rw");
    FileChannel lockChannel = null;
    FileLock cacheLock = null;
    List<ExtractedDex> files;
    IOException releaseLockException = null;
    try {
        lockChannel = lockRaf.getChannel();
        Log.i(TAG, "Blocking on lock " + lockFile.getPath());
        cacheLock = lockChannel.lock();
        Log.i(TAG, lockFile.getPath() + " locked");
        if (!forceReload && !isModified(context, sourceApk, currentCrc, prefsKeyPrefix)) {
            try {
                files = loadExistingExtractions(context, sourceApk, dexDir, prefsKeyPrefix);
            } catch (IOException ioe) {
                Log.w(TAG, "Failed to reload existing extracted secondary dex files," + " falling back to fresh extraction", ioe);
                files = performExtractions(sourceApk, dexDir);
                putStoredApkInfo(context, prefsKeyPrefix, getTimeStamp(sourceApk), currentCrc, files);
            }
        } else {
            Log.i(TAG, "Detected that extraction must be performed.");
            files = performExtractions(sourceApk, dexDir);
            putStoredApkInfo(context, prefsKeyPrefix, getTimeStamp(sourceApk), currentCrc, files);
        }
    } finally {
        if (cacheLock != null) {
            try {
                cacheLock.release();
            } catch (IOException e) {
                Log.e(TAG, "Failed to release lock on " + lockFile.getPath());
                // Exception while releasing the lock is bad, we want to report it, but not at
                // the price of overriding any already pending exception.
                releaseLockException = e;
            }
        }
        if (lockChannel != null) {
            closeQuietly(lockChannel);
        }
        closeQuietly(lockRaf);
    }
    if (releaseLockException != null) {
        throw releaseLockException;
    }
    Log.i(TAG, "load found " + files.size() + " secondary dex files");
    return files;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ZipFile(java.util.zip.ZipFile)

Example 98 with FileLock

use of java.nio.channels.FileLock in project atlas by alibaba.

the class AtlasFileLock method LockExclusive.

/*
     * Hold a exclusive lock, file is the directory
     */
public boolean LockExclusive(File orgFile) {
    RandomAccessFile fOs = null;
    FileChannel fChannel = null;
    try {
        if (orgFile == null) {
            return false;
        }
        File file;
        if (orgFile.exists() && orgFile.isDirectory()) {
            file = new File(orgFile.getAbsolutePath().concat("/lock"));
        } else {
            file = new File(orgFile.getParentFile().getAbsolutePath().concat("/lock"));
        }
        if (file.exists() != true) {
            file.createNewFile();
        }
        fOs = new RandomAccessFile(file.getAbsolutePath(), "rw");
        fChannel = fOs.getChannel();
        FileLock fFileLock = fChannel.lock();
        if (fFileLock.isValid()) {
            RefCntInc(file.getAbsolutePath(), fFileLock, fOs, fChannel);
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) IOException(java.io.IOException)

Example 99 with FileLock

use of java.nio.channels.FileLock in project atlas by alibaba.

the class FileLockUtils method lock.

public static boolean lock(File file, Runnable runnable) {
    try {
        File lockFile = file;
        if (lockFile.isDirectory()) {
            lockFile = new File(lockFile, ".atlaslock");
        }
        RandomAccessFile randomAccessFile;
        FileLock fileLock;
        try {
            randomAccessFile = new RandomAccessFile(lockFile, "rw");
            fileLock = randomAccessFile.getChannel().tryLock();
        } catch (Exception e) {
            throw new GradleException(e.getMessage(), e);
        }
        if (fileLock != null) {
            File finalLockFile = lockFile;
            Runtime.getRuntime().addShutdownHook(new Thread() {

                @Override
                public void run() {
                    try {
                        fileLock.release();
                        randomAccessFile.close();
                        finalLockFile.delete();
                    } catch (Exception e) {
                        log.error("Unable to remove lock file: " + file.getAbsolutePath(), e);
                    }
                }
            });
            runnable.run();
            lockFile.delete();
            return true;
        }
    } finally {
    }
    return false;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) GradleException(org.gradle.api.GradleException) FileLock(java.nio.channels.FileLock) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) GradleException(org.gradle.api.GradleException)

Example 100 with FileLock

use of java.nio.channels.FileLock in project helios by spotify.

the class JobPrefixFile method tryFromExistingFile.

/**
 * Attempts to lock the given file, and create a JobPrefixFile for it. A new JobPrefixFile
 * instance will be returned if a lock can be obtained for the file. Null will be returned if the
 * lock is already held by either this process or another. For all other cases, an exception will
 * be thrown.
 *
 * @param file the path to the file
 *
 * @return a new JobPrefixFile if a file lock can be obtained. Null if a lock for the file is
 *         already held by either this process or another.
 */
public static JobPrefixFile tryFromExistingFile(final Path file) throws IOException {
    Preconditions.checkNotNull(file);
    final FileChannel channel = FileChannel.open(file, WRITE);
    final FileLock lock;
    try {
        // We want to return JobPrefixFile if we can obtain the lock, null if someone already holds
        // the lock, and throw an exception in all other cases. tryLock makes this a little tricky.
        // It's behavior this:
        // - returns a FileLock if one can be obtained
        // - returns null if another process holds the lock
        // - throws OverlappingFileLockException if the lock is already held by this process
        // - throws a various exceptions for other errors
        lock = channel.tryLock();
    } catch (OverlappingFileLockException e) {
        // If the lock is already held by this process, close the channel and return null.
        close(channel);
        return null;
    } catch (Exception e) {
        // If an unexpected error occurred, close the channel and rethrow.
        close(channel);
        throw e;
    }
    // If another process hold the lock, close the channel and return null.
    if (lock == null) {
        close(channel);
        return null;
    }
    // If we've obtained the lock, return a new JobPrefixFile
    return new JobPrefixFile(file, channel, lock);
}
Also used : FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) IOException(java.io.IOException)

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