本文整理了Java中java.nio.channels.FileLock
类的一些代码示例,展示了FileLock
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。FileLock
类的具体详情如下:
包路径:java.nio.channels.FileLock
类名称:FileLock
[英]A FileLock represents a locked region of a file.
Locks have certain properties that enable collaborating processes to avoid the lost update problem or reading inconsistent data. Logically, a file lock can be exclusive or shared. Multiple processes can hold shared locks on the same region of a file, but only a single process can hold an exclusive lock on a given region of a file and no other process can simultaneously hold a shared lock overlapping the exclusive lock. An application can determine whether a FileLock is shared or exclusive via the isShared() method.
Locks held by a particular process cannot overlap one another. Applications can determine whether a proposed lock will overlap by using the overlaps(long, long)) method. Locks held in other processes may overlap locks held in this process. Locks are shared amongst all threads in the acquiring process, and are therefore unsuitable for intra-process synchronization.
Once a lock is acquired, it is immutable in all its state except isValid(). The lock will initially be valid, but may be rendered invalid by explicit removal of the lock, using release(), or implicitly by closing the channel or exiting the process (terminating the VM).
Locks are intended to be true platform operating system file locks, and therefore locks held by the VM will be visible to other operating system processes.
The characteristics of the underlying operating system locks will show through in the Java implementation. For example, some platforms' locks are 'mandatory' -- meaning the operating system enforces the locks on processes that attempt to access locked regions of files; whereas other platforms' locks are only 'advisory' -- meaning that processes are required to collaborate to ensure locks are acquired and there is a potential for processes to not play well. To be on the safe side, it is best to assume that the platform is adopting advisory locks and always acquire shared locks when reading a region of a file.
On some platforms, the presence of a lock will prevent the file from being memory-mapped. On some platforms, closing a channel on a given file handle will release all the locks held on that file -- even if there are other channels open on the same file; their locks will also be released. The safe option here is to ensure that you only acquire locks on a single channel for a particular file and that becomes the synchronization point.
Further care should be exercised when locking files maintained on network file systems, since they often have further limitations.
[中]FileLock表示文件的锁定区域。
锁具有某些属性,使协作进程能够避免丢失更新问题或读取不一致的数据。从逻辑上讲,文件锁可以是“独占”或“共享”。多个进程可以在文件的同一区域上持有共享锁,但只有一个进程可以在文件的给定区域上持有独占锁,并且没有其他进程可以同时持有与独占锁重叠的共享锁。应用程序可以通过isShared()方法确定文件锁是共享的还是独占的。
特定进程持有的锁不能相互重叠。应用程序可以使用overlaps(long,long))方法确定提议的锁是否会重叠。其他进程中持有的锁可能与此进程中持有的锁重叠。锁在获取进程中的所有线程之间共享,因此不适合进程内同步。
一旦获得锁,它在除isValid()之外的所有状态下都是不可变的。锁最初是有效的,但可能会通过使用release()显式删除锁,或通过关闭通道或退出进程(终止VM)隐式删除锁而变得无效。
####平台依赖关系
锁旨在成为真正的平台操作系统文件锁,因此VM持有的锁将对其他操作系统进程可见。
底层操作系统锁的特性将在Java实现中显示出来。例如,一些平台的锁是“强制”的——这意味着操作系统在试图访问文件锁定区域的进程上强制执行锁;而其他平台的锁只是“建议性的”——这意味着需要流程协作以确保获得锁,并且流程可能无法正常运行。为了安全起见,最好假设平台采用建议锁,并且在读取文件区域时始终获取共享锁。
在某些平台上,存在锁会阻止文件被内存映射。在某些平台上,关闭给定文件句柄上的通道将释放该文件上的所有锁——即使同一文件上有其他打开的通道;他们的锁也将被释放。这里的安全选项是确保只为特定文件获取单个通道上的锁,并且该通道成为同步点。
在锁定网络文件系统上维护的文件时,应更加小心,因为它们通常有进一步的限制。
代码示例来源:origin: stackoverflow.com
FileInputStream in = new FileInputStream(file);
try {
java.nio.channels.FileLock lock = in.getChannel().lock();
try {
Reader reader = new InputStreamReader(in, charset);
...
} finally {
lock.release();
}
} finally {
in.close();
}
代码示例来源:origin: apache/geode
void closeLockFile() {
FileLock myfl = this.fl;
if (myfl != null) {
try {
FileChannel fc = myfl.channel();
if (myfl.isValid()) {
myfl.release();
}
fc.close();
} catch (IOException ignore) {
}
this.fl = null;
}
File f = this.lockFile;
if (f != null) {
if (f.delete()) {
if (logger.isDebugEnabled()) {
logger.debug("Deleted lock file {}", f);
}
} else if (f.exists()) {
if (logger.isDebugEnabled()) {
logger.debug("Could not delete lock file {}", f);
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Unlocked disk store {}", name);
}
}
代码示例来源:origin: javamelody/javamelody
void release() throws IOException {
try {
if (fileLock != null && fileLock.isValid()) {
fileLock.release();
}
} finally {
try {
if (fileChannel != null) {
fileChannel.close();
}
} finally {
if (input != null) {
input.close();
}
}
}
}
代码示例来源:origin: apache/flume
/**
* Unlock directory.
*
* @throws IOException
*/
private void unlock(File dir) throws IOException {
FileLock lock = locks.remove(dir.getAbsolutePath());
if (lock == null) {
return;
}
lock.release();
lock.channel().close();
lock = null;
}
代码示例来源:origin: spotify/helios
public void release() {
if (!lock.isValid()) {
log.debug("lock already released: {}", path);
return;
}
try {
lock.release();
} catch (Exception e) {
log.warn("caught exception releasing port lock: {}", path, e);
}
try {
file.close();
} catch (Exception e) {
log.warn("caught exception closing port lock file: {}", path, e);
}
try {
Files.deleteIfExists(path);
} catch (Exception e) {
log.warn("caught exception deleting port lock file: {}", path, e);
}
}
}
代码示例来源:origin: apache/geode
protected int currentValue() throws IOException {
try (FileOutputStream out = new FileOutputStream(lockFile)) {
java.nio.channels.FileLock lock = out.getChannel().lock();
try {
String fileContents = FileUtils.readFileToString(dataFile, Charsets.UTF_8);
return Integer.valueOf(fileContents);
} finally {
lock.release();
}
}
}
}
代码示例来源:origin: apache/maven
Properties props = new Properties();
in = new FileInputStream( touchfile );
lock = in.getChannel().lock( 0, Long.MAX_VALUE, true );
props.load( in );
lock.release();
lock = null;
in.close();
in = null;
lock.release();
代码示例来源:origin: apache/incubator-dubbo
lockfile.createNewFile();
try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
FileChannel channel = raf.getChannel()) {
FileLock lock = channel.tryLock();
if (lock == null) {
throw new IOException("Can not lock the metadataReport cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties");
file.createNewFile();
try (FileOutputStream outputFile = new FileOutputStream(file)) {
properties.store(outputFile, "Dubbo metadataReport Cache");
lock.release();
代码示例来源:origin: apache/maven
try
Properties props = new Properties();
channel = new RandomAccessFile( touchfile, "rw" ).getChannel();
lock = channel.lock();
props.load( Channels.newInputStream( channel ) );
props.setProperty( key, Long.toString( System.currentTimeMillis() ) );
channel.truncate( 0 );
props.store( Channels.newOutputStream( channel ), "Last modified on: " + new Date() );
lock.release();
lock = null;
channel.close();
channel = null;
lock.release();
代码示例来源:origin: soabase/exhibitor
@Override
public LoadedInstanceConfig loadConfig() throws Exception
{
File propertiesFile = new File(propertiesDirectory, propertyFileName);
Properties properties = new Properties();
if ( propertiesFile.exists() )
{
RandomAccessFile raf = new RandomAccessFile(propertiesFile, "rw");
try
{
FileLock lock = raf.getChannel().lock();
try
{
properties.load(Channels.newInputStream(raf.getChannel()));
}
finally
{
lock.release();
}
}
finally
{
CloseableUtils.closeQuietly(raf);
}
}
PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig(properties, defaults);
return new LoadedInstanceConfig(config, propertiesFile.lastModified());
}
代码示例来源:origin: pockethub/PocketHub
boolean delete = false;
try {
dir = new RandomAccessFile(handle, "rw");
lock = dir.getChannel().lock();
input = new ObjectInputStream(new GZIPInputStream(
new FileInputStream(dir.getFD()), 8192 * 8));
int streamVersion = input.readInt();
if (streamVersion != version) {
lock.release();
} catch (IOException e) {
Log.d(TAG, "Exception unlocking file", e);
代码示例来源:origin: gocd/gocd
public synchronized void writeToConfigXmlFile(String content) {
FileChannel channel = null;
FileOutputStream outputStream = null;
FileLock lock = null;
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
channel = randomAccessFile.getChannel();
lock = channel.lock();
randomAccessFile.seek(0);
randomAccessFile.setLength(0);
outputStream = new FileOutputStream(randomAccessFile.getFD());
IOUtils.write(content, outputStream, UTF_8);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (channel != null && lock != null) {
try {
lock.release();
channel.close();
IOUtils.closeQuietly(outputStream);
} catch (IOException e) {
LOGGER.error("Error occured when releasing file lock and closing file.", e);
}
}
}
}
代码示例来源:origin: oracle/helidon
try (FileInputStream fis = new FileInputStream(path.toFile())) {
FileLock lock = null;
try {
lock = fis.getChannel().tryLock(0L, Long.MAX_VALUE, false);
} catch (NonWritableChannelException e) {
lock.release();
代码示例来源:origin: geotools/geotools
while ((ze = zin.getNextEntry()) != null) {
FileOutputStream fout =
new FileOutputStream(new File(directory, ze.getName()));
while ((read = zin.read(buf)) > 0) {
fout.write(buf, 0, read);
fout.close();
if (lock != null) {
try {
lock.release();
lock.channel().close();
new File(directory, LOCK_FILE).delete();
} catch (IOException e) {
代码示例来源:origin: pockethub/PocketHub
try {
createDirectory(handle.getParentFile());
dir = new RandomAccessFile(handle, "rw");
lock = dir.getChannel().lock();
output = new ObjectOutputStream(new GZIPOutputStream(
new FileOutputStream(dir.getFD()), 8192));
output.writeInt(version);
output.writeObject(request);
lock.release();
} catch (IOException e) {
Log.d(TAG, "Exception unlocking file", e);
代码示例来源:origin: knightliao/disconf
outStream = new FileOutputStream(lockFile);
FileChannel channel = outStream.getChannel();
lock = channel.tryLock();
if (lock != null) {
lock.release();
} catch (IOException e) {
logger.warn(e.toString());
outStream.close();
} catch (IOException e) {
logger.warn(e.toString());
代码示例来源:origin: stackoverflow.com
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();
/*
use channel.lock OR channel.tryLock();
*/
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
// Release the lock - if it is not null!
if( lock != null ) {
lock.release();
}
// Close the file
channel.close();
} catch (Exception e) {
}
代码示例来源:origin: xap/xap
@Override
public String get(String key) throws IOException {
FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
FileLock fileLock = fileChannel.lock();
try {
Properties p = readPropertiesFromChannel(fileChannel);
return p.getProperty(key);
} finally {
fileLock.release();
fileChannel.close();
}
}
代码示例来源:origin: xap/xap
@Override
public String set(String key, String value) throws IOException {
FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
FileLock fileLock = fileChannel.lock();
String oldValue = null;
try {
Properties p = readPropertiesFromChannel(fileChannel);
oldValue = (String) p.setProperty(key, value);
writePropertiesToChannel(fileChannel, p);
} finally {
fileLock.release();
fileChannel.close();
}
return oldValue;
}
代码示例来源:origin: graphhopper/graphhopper
public static void main(String[] args) throws IOException {
// trying FileLock mechanics in different processes
File file = new File("tmp.lock");
file.createNewFile();
FileChannel channel = new RandomAccessFile(file, "r").getChannel();
boolean shared = true;
FileLock lock1 = channel.tryLock(0, Long.MAX_VALUE, shared);
System.out.println("locked " + lock1);
System.in.read();
System.out.println("release " + lock1);
lock1.release();
}
内容来源于网络,如有侵权,请联系作者删除!