Search in sources :

Example 6 with FileLock

use of java.nio.channels.FileLock in project android_frameworks_base by ParanoidAndroid.

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 7 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 8 with FileLock

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

the class AbstractRegistry method doSaveProperties.

public void doSaveProperties(long version) {
    if (version < lastCacheChanged.get()) {
        return;
    }
    if (file == null) {
        return;
    }
    Properties newProperties = new Properties();
    // 保存之前先读取一遍,防止多个注册中心之间冲突
    InputStream in = null;
    try {
        if (file.exists()) {
            in = new FileInputStream(file);
            newProperties.load(in);
        }
    } catch (Throwable e) {
        logger.warn("Failed to load registry store file, cause: " + e.getMessage(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.warn(e.getMessage(), e);
            }
        }
    }
    // 保存
    try {
        newProperties.putAll(properties);
        File lockfile = new File(file.getAbsolutePath() + ".lock");
        if (!lockfile.exists()) {
            lockfile.createNewFile();
        }
        RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
        try {
            FileChannel channel = raf.getChannel();
            try {
                FileLock lock = channel.tryLock();
                if (lock == null) {
                    throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties");
                }
                // 保存
                try {
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    FileOutputStream outputFile = new FileOutputStream(file);
                    try {
                        newProperties.store(outputFile, "Dubbo Registry Cache");
                    } finally {
                        outputFile.close();
                    }
                } finally {
                    lock.release();
                }
            } finally {
                channel.close();
            }
        } finally {
            raf.close();
        }
    } catch (Throwable e) {
        if (version < lastCacheChanged.get()) {
            return;
        } else {
            registryCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet()));
        }
        logger.warn("Failed to save registry store file, cause: " + e.getMessage(), e);
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileChannel(java.nio.channels.FileChannel) FileOutputStream(java.io.FileOutputStream) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException) Properties(java.util.Properties) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 9 with FileLock

use of java.nio.channels.FileLock in project disconf by knightliao.

the class OsUtil method transferFileAtom.

/**
     * @param src
     * @param dest
     *
     * @return void
     *
     * @Description: 具有重试机制的 ATOM 转移文件 ,并且会校验文件是否一致 才替换
     * @author liaoqiqi
     * @date 2013-6-20
     */
public static void transferFileAtom(File src, File dest, boolean isDeleteSource) throws Exception {
    // 文件锁所在文件
    File lockFile = new File(dest + ".lock");
    FileOutputStream outStream = null;
    FileLock lock = null;
    try {
        int tryTime = 0;
        while (tryTime < 3) {
            try {
                outStream = new FileOutputStream(lockFile);
                FileChannel channel = outStream.getChannel();
                lock = channel.tryLock();
                if (lock != null) {
                    if (dest.exists()) {
                        // 判断内容是否一样
                        if (FileUtils.isFileEqual(src, dest)) {
                            // 内容如果一样,就只需要删除源文件就行了
                            if (isDeleteSource) {
                                src.delete();
                            }
                            break;
                        }
                    }
                    logger.debug("start to replace " + src.getAbsolutePath() + " to " + dest.getAbsolutePath());
                    // 转移
                    transferFile(src, dest);
                    // 删除源文件
                    if (isDeleteSource) {
                        src.delete();
                    }
                    break;
                }
            } catch (FileNotFoundException e) {
                // 打不开文件,则后面进行重试
                logger.warn(e.toString());
            } finally {
                // 释放锁,通道;删除锁文件
                if (null != lock) {
                    try {
                        lock.release();
                    } catch (IOException e) {
                        logger.warn(e.toString());
                    }
                    if (lockFile != null) {
                        lockFile.delete();
                    }
                }
                if (outStream != null) {
                    try {
                        outStream.close();
                    } catch (IOException e) {
                        logger.warn(e.toString());
                    }
                }
            }
            // 进行重试
            logger.warn("try lock failed. sleep and try " + tryTime);
            tryTime++;
            try {
                Thread.sleep(1000 * tryTime);
            } catch (Exception e) {
                System.out.print("");
            }
        }
    } catch (IOException e) {
        logger.warn(e.toString());
    }
}
Also used : FileChannel(java.nio.channels.FileChannel) FileOutputStream(java.io.FileOutputStream) FileLock(java.nio.channels.FileLock) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) File(java.io.File) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 10 with FileLock

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

the class SingleFilePageSwapperTest method creatingSwapperForInternallyLockedFileMustThrow.

@Test
public void creatingSwapperForInternallyLockedFileMustThrow() throws Exception {
    // no file locking on Windows.
    assumeFalse("No file locking on Windows", SystemUtils.IS_OS_WINDOWS);
    PageSwapperFactory factory = createSwapperFactory();
    factory.setFileSystemAbstraction(fileSystem);
    File file = testDir.file("file");
    StoreFileChannel channel = fileSystem.create(file);
    try (FileLock fileLock = channel.tryLock()) {
        assertThat(fileLock, is(not(nullValue())));
        expectedException.expect(FileLockException.class);
        createSwapper(factory, file, 4, NO_CALLBACK, true);
    }
}
Also used : PageSwapperFactory(org.neo4j.io.pagecache.PageSwapperFactory) StoreFileChannel(org.neo4j.io.fs.StoreFileChannel) FileLock(java.nio.channels.FileLock) File(java.io.File) PageSwapperTest(org.neo4j.io.pagecache.PageSwapperTest) Test(org.junit.Test)

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