Search in sources :

Example 21 with FileLock

use of java.nio.channels.FileLock in project platform_frameworks_base by android.

the class MiniThumbFile method saveMiniThumbToFile.

public synchronized void saveMiniThumbToFile(byte[] data, long id, long magic) throws IOException {
    RandomAccessFile r = miniThumbDataFile();
    if (r == null)
        return;
    long pos = id * BYTES_PER_MINTHUMB;
    FileLock lock = null;
    try {
        if (data != null) {
            if (data.length > BYTES_PER_MINTHUMB - HEADER_SIZE) {
                // not enough space to store it.
                return;
            }
            mBuffer.clear();
            mBuffer.put((byte) 1);
            mBuffer.putLong(magic);
            mBuffer.putInt(data.length);
            mBuffer.put(data);
            mBuffer.flip();
            lock = mChannel.lock(pos, BYTES_PER_MINTHUMB, false);
            mChannel.write(mBuffer, pos);
        }
    } catch (IOException ex) {
        Log.e(TAG, "couldn't save mini thumbnail data for " + id + "; ", ex);
        throw ex;
    } catch (RuntimeException ex) {
        // Other NIO related exception like disk full, read only channel..etc
        Log.e(TAG, "couldn't save mini thumbnail data for " + id + "; disk full or mount read-only? " + ex.getClass());
    } finally {
        try {
            if (lock != null)
                lock.release();
        } catch (IOException ex) {
        // ignore it.
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException)

Example 22 with FileLock

use of java.nio.channels.FileLock in project CoreNLP by stanfordnlp.

the class FileBackedCache method acquireFileLock.

@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
protected FileSemaphore acquireFileLock(File f) throws IOException {
    assert canonicalFile.intern(f.getCanonicalFile()) == f;
    synchronized (f) {
        // Check semaphore
        synchronized (fileLocks) {
            if (fileLocks.containsKey(f)) {
                FileSemaphore sem = fileLocks.get(f);
                if (sem.isActive()) {
                    sem.take();
                    return sem;
                } else {
                    fileLocks.remove(f);
                }
            }
        }
        // Get the channel
        FileChannel channel = new RandomAccessFile(f, "rw").getChannel();
        FileLock lockOrNull = null;
        // Try the lock
        for (int i = 0; i < 1000; ++i) {
            lockOrNull = channel.tryLock();
            if (lockOrNull == null || !lockOrNull.isValid()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log(e);
                    throw new RuntimeInterruptedException(e);
                }
                if (i % 60 == 59) {
                    warn("FileBackedCache", "Lock still busy after " + ((i + 1) / 60) + " minutes");
                }
                //noinspection UnnecessaryContinue
                continue;
            } else {
                break;
            }
        }
        if (lockOrNull == null) {
            warn("FileBackedCache", "Could not acquire file lock! Continuing without lock");
        }
        // Return
        FileSemaphore sem = new FileSemaphore(lockOrNull, channel);
        synchronized (fileLocks) {
            fileLocks.put(f, sem);
        }
        return sem;
    }
}
Also used : FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock)

Example 23 with FileLock

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

the class LockFile method execute.

@Override
public void execute() throws Exception {
    if (state.containsKey("lockedFile")) {
        throw new Exception("Currently only one file can be locked at a time.");
    }
    File file = pickFile(7878);
    log(this, file.getAbsolutePath());
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    FileLock fileLock = randomAccessFile.getChannel().lock();
    state.put(STATE_KEY_RANDOM_ACCESS_FILE, randomAccessFile);
    state.put(STATE_KEY_FILE_LOCK, fileLock);
// Do not (!) close this file
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileLock(java.nio.channels.FileLock) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 24 with FileLock

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

the class FileUtilTest method testFileLocked.

@Test
public void testFileLocked() throws Exception {
    // Setup
    File tempDir = TestFileUtil.createTempDirectoryInSystemTemp();
    // Run
    File lockedFile = TestFileUtil.createRandomFileInDirectory(tempDir, 50 * 1024);
    // Test
    assertFalse("File should not be locked: " + lockedFile, FileUtil.isFileLocked(lockedFile));
    RandomAccessFile fileLock = new RandomAccessFile(lockedFile, "rw");
    FileLock lockedFileLock = fileLock.getChannel().lock();
    assertTrue("File should be locked: " + lockedFile, FileUtil.isFileLocked(lockedFile));
    // Tear down
    lockedFileLock.release();
    fileLock.close();
    Path bFilePath = Paths.get(lockedFile.getAbsolutePath());
    if (EnvironmentUtil.isWindows()) {
        Files.setAttribute(bFilePath, "dos:readonly", true);
    } else if (EnvironmentUtil.isUnixLikeOperatingSystem()) {
        Files.setPosixFilePermissions(bFilePath, PosixFilePermissions.fromString("r--r--r--"));
    }
    assertFalse("File should not be locked if read-only: " + lockedFile, FileUtil.isFileLocked(lockedFile));
    // Tear down
    TestFileUtil.deleteDirectory(tempDir);
}
Also used : Path(java.nio.file.Path) RandomAccessFile(java.io.RandomAccessFile) FileLock(java.nio.channels.FileLock) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) Test(org.junit.Test)

Example 25 with FileLock

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

the class FileUtil method isFileLocked.

public static boolean isFileLocked(File file) {
    if (!file.exists()) {
        return false;
    }
    if (file.isDirectory()) {
        return false;
    }
    if (isSymlink(file)) {
        return false;
    }
    RandomAccessFile randomAccessFile = null;
    boolean fileLocked = false;
    try {
        // Test 1 missing permissions or locked file parts. If File is not readable == locked
        randomAccessFile = new RandomAccessFile(file, "r");
        randomAccessFile.close();
    } catch (Exception e) {
        fileLocked = true;
    }
    if (!fileLocked && file.canWrite()) {
        try {
            // Test 2:Locked file parts
            randomAccessFile = new RandomAccessFile(file, "rw");
            // Test 3: Set lock and release it again
            FileLock fileLock = randomAccessFile.getChannel().tryLock();
            if (fileLock == null) {
                fileLocked = true;
            } else {
                try {
                    fileLock.release();
                } catch (Exception e) {
                /* Nothing */
                }
            }
        } catch (Exception e) {
            fileLocked = true;
        }
        if (randomAccessFile != null) {
            try {
                randomAccessFile.close();
            } catch (IOException e) {
            /* Nothing */
            }
        }
    }
    return fileLocked;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException) IOException(java.io.IOException) InvalidPathException(java.nio.file.InvalidPathException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

FileLock (java.nio.channels.FileLock)130 RandomAccessFile (java.io.RandomAccessFile)69 IOException (java.io.IOException)68 File (java.io.File)44 FileChannel (java.nio.channels.FileChannel)33 OverlappingFileLockException (java.nio.channels.OverlappingFileLockException)22 Test (org.junit.Test)12 FileOutputStream (java.io.FileOutputStream)10 FileInputStream (java.io.FileInputStream)5 ByteBuffer (java.nio.ByteBuffer)4 NonWritableChannelException (java.nio.channels.NonWritableChannelException)4 FileNotFoundException (java.io.FileNotFoundException)3 NonReadableChannelException (java.nio.channels.NonReadableChannelException)3 NoSuchFileException (java.nio.file.NoSuchFileException)3 Path (java.nio.file.Path)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 Properties (java.util.Properties)3 FileSystemOperationException (com.axway.ats.common.filesystem.FileSystemOperationException)2 AttributeNotSupportedException (com.axway.ats.core.filesystem.exceptions.AttributeNotSupportedException)2 FileDoesNotExistException (com.axway.ats.core.filesystem.exceptions.FileDoesNotExistException)2