本文整理匯總了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;
}
}
示例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);
}
}
}
}
示例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();
}
}
示例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;
}
示例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();
}
}