當前位置: 首頁>>代碼示例>>Java>>正文


Java FileChannel.lock方法代碼示例

本文整理匯總了Java中java.nio.channels.FileChannel.lock方法的典型用法代碼示例。如果您正苦於以下問題:Java FileChannel.lock方法的具體用法?Java FileChannel.lock怎麽用?Java FileChannel.lock使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.nio.channels.FileChannel的用法示例。


在下文中一共展示了FileChannel.lock方法的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: LockExclusive

import java.nio.channels.FileChannel; //導入方法依賴的package包/類
public boolean LockExclusive(File targetFile) {

            if (targetFile == null) {
                return false;
            }
            try {
                File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
                if (!lockFile.exists()) {
                    lockFile.createNewFile();
                }
                RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile.getAbsolutePath(), "rw");
                FileChannel channel = randomAccessFile.getChannel();
                java.nio.channels.FileLock lock = channel.lock();
                if (!lock.isValid()) {
                    return false;
                }
                RefCntInc(lockFile.getAbsolutePath(), lock, randomAccessFile, channel);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
 
開發者ID:7763sea,項目名稱:VirtualHook,代碼行數:23,代碼來源:FileUtils.java

示例2: lockFile

import java.nio.channels.FileChannel; //導入方法依賴的package包/類
/**
 * <pre>
 * Acquires an exclusive lock on a file
 *
 * <b>Platform dependencies</b>
 *
 * - In Windows it works as expected
 * - In Linux it depends on the locking mechanism of the system. The file locking types are two - advisory and mandatory:
 *
 *    a) <b>Advisory locking</b> - advisory locking will work, only if the participating process are cooperative.
 *       Advisory locking sometimes also called as "unenforced" locking.
 *
 *    b) <b>Mandatory locking</b> - mandatory locking doesn’t require cooperation from the participating processes.
 *       It causes the kernel to check every open, read and write to verify that the calling process isn’t
 *       violating a lock on the given file. To enable mandatory locking in Linux, you need to enable it on
 *       a file system level and also on the individual files. The steps to be followed are:
 *           1. Mount the file system with "<i>-o mand</i>" option
 *           2. For the lock_file, turn on the set-group-ID bit and turn off the group-execute bit, to enable
 *              mandatory locking on that particular file. (This way has been chosen because when you turn off
 *              the group-execute bit, set-group-ID has no real meaning to it )
 *
 *       How to do mandatory locking:
 *           Note: You need to be root to execute the below command
 *           <i># mount -oremount,mand /</i>
 *           <i># touch mandatory.txt</i>
 *           <i># chmod g+s,g-x mandatory.txt</i>
 * </pre>
 *
 * @param fileName file name
 */
@Override
public void lockFile(
                      String fileName ) {

    synchronized (lockedFiles) {

        if (lockedFiles.containsKey(fileName)) {

            log.warn("File '" + fileName + "' is already locked");
        } else {

            try {
                File fileToLock = new File(fileName);
                @SuppressWarnings( "resource")
                //keep lock to the file
                FileChannel channel = new RandomAccessFile(fileToLock, "rw").getChannel();

                FileLock fileLock = channel.lock();
                lockedFiles.put(fileName, fileLock);
            } catch (FileNotFoundException fnfe) {
                throw new FileSystemOperationException("File '" + fileName + "' is not found", fnfe);
            } catch (OverlappingFileLockException ofle) {
                throw new FileSystemOperationException("File '" + fileName
                                                       + "' is already locked in the current JVM"
                                                       + ", but not from this class, so we can't unlock it later.",
                                                       ofle);
            } catch (Exception e) {
                throw new FileSystemOperationException("Could not lock file '" + fileName + "'", e);
            }
        }
    }
}
 
開發者ID:Axway,項目名稱:ats-framework,代碼行數:63,代碼來源:LocalFileSystemOperations.java

示例3: shouldThrowLockExceptionIfFailedToLockStateDirectory

import java.nio.channels.FileChannel; //導入方法依賴的package包/類
@Test
public void shouldThrowLockExceptionIfFailedToLockStateDirectory() throws Exception {
    final File taskDirectory = stateDirectory.directoryForTask(taskId);
    final FileChannel channel = FileChannel.open(new File(taskDirectory,
                                                          StateDirectory.LOCK_FILE_NAME).toPath(),
                                                 StandardOpenOption.CREATE,
                                                 StandardOpenOption.WRITE);
    // lock the task directory
    final FileLock lock = channel.lock();

    try {
        new ProcessorStateManager(
            taskId,
            noPartitions,
            false,
            stateDirectory,
            Collections.<String, String>emptyMap(),
            changelogReader,
            false);
        fail("Should have thrown LockException");
    } catch (final LockException e) {
       // pass
    } finally {
        lock.release();
        channel.close();
    }
}
 
開發者ID:YMCoding,項目名稱:kafka-0.11.0.0-src-with-comment,代碼行數:28,代碼來源:ProcessorStateManagerTest.java

示例4: load

import java.nio.channels.FileChannel; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:alibaba,項目名稱:atlas,代碼行數:71,代碼來源:MultiDexExtractor.java

示例5: TestMultipleFD

import java.nio.channels.FileChannel; //導入方法依賴的package包/類
/**
 * Exercise FileDispatcher close()/preClose()
 */
private static void TestMultipleFD() throws Exception {
    RandomAccessFile raf = null;
    FileOutputStream fos = null;
    FileInputStream fis = null;
    FileChannel fc = null;
    FileLock fileLock = null;

    File test1 = new File("test1");
    try {
        raf = new RandomAccessFile(test1, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fis != null) fis.close();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        test1.delete();
    }

    /*
     * Close out in different order to ensure FD is not
     * closed out too early
     */
    File test2 = new File("test2");
    try {
        raf = new RandomAccessFile(test2, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (raf != null) raf.close();
        if (fos != null) fos.close();
        if (fis != null) fis.close();
        test2.delete();
    }

    // one more time, fos first this time
    File test3 = new File("test3");
    try {
        raf = new RandomAccessFile(test3, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        if (fis != null) fis.close();
        test3.delete();
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:70,代碼來源:Sharing.java


注:本文中的java.nio.channels.FileChannel.lock方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。