当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Java OverlappingFileLockException用法及代码示例

当尝试获取与该进程持有的现有锁或挂起锁重叠的锁时,会引发OverlappingFileLockException。

如果请求的锁定区域与该 JVM 中的某个线程已经持有的文件锁重叠,或者该 JVM 中已经有一个线程等待锁定,则 FileChannel 的 lock( ) 和 tryLock( ) 方法将抛出此异常同一文件的重叠区域。 FileChannel 文件锁定机制旨在锁定文件以防止两个单独进程的并发访问。同一 JVM 中的两个线程不应尝试获取同一文件的重叠区域的锁,任何尝试这样做都会导致引发此类异常。

封装视图

java.lang.Object
    java.lang.Throwable
         java.lang.Exception
              java.lang.RuntimeException
                   java.lang.IllegalStateException
                    java.nio.channels.OverlappingFileLockException

Remember: It does implement Serializable interface.

用法:

public class OverlappingFileLockException
extends IllegalStateException

Note: An unchecked exception is thrown when an attempt is made to acquire a lock on a region of a file that overlaps a region already locked by the same Java virtual machine, or when another thread is already waiting to lock an overlapping region of the same file.

构造函数总结

  • OverlappingFileLockException():构造该类的一个实例。

执行:

在此示例中,我们将向您展示如何在 Java 中创建共享文件锁并处理 OverlappingFileLockException。使用 Java NIO 通道创建共享文件锁意味着应该:

  1. 创建一个 File 对象来封装要锁定的文件系统中的实际文件
  2. 创建随机访问文件流(读写)。为此,您必须首先创建一个RandomAccessFile对象来封装上面创建的文件对象并打开它进行读写操作。然后使用RandomAccessFile对象的getChannel() API方法获取文件通道以读取/写入数据
  3. 使用 FileChannel 类的 lock(long, long, boolean) API 方法获取此通道文件的独占锁。该方法会阻塞,直到该区域可以被锁定或该通道被关闭或调用线程被中断为止。布尔属性将锁标记为共享或非共享。该方法返回 FileLock 类的句柄以利用锁
  4. 或者,我们可以使用 FileChannel 类的 tryLock(long, long, boolean) API 方法。该方法尝试获取该通道文件的独占锁,但不会阻塞;调用总是立即返回,无论是获取了所请求区域的锁还是未能获取锁。

示例 1

Java


// Java Program to Illustrate Shared lock over File
// Importing required classes
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
// Main class
// CreateSharedFileLockOnFile
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Try block to check for exceptions
        try {
            // Creating a file
            File file = new File("fileToLock.dat");
            // Creates a random access file stream to read
            // from, and optionally to write to
            FileChannel channel
                = new RandomAccessFile(file, "rw")
                      .getChannel();
            // Acquire an exclusive lock on this channel's
            // file ( block until the region can be locked,
            // this channel is closed, or the invoking
            // thread is interrupted)
            FileLock lock
                = channel.lock(0, Long.MAX_VALUE, true);
            // Attempts to acquire an exclusive lock on this
            // channel's file (does not block, an invocation
            // always returns immediately, either having
            // acquired a lock on the requested region or
            // having failed to do so.
            try {
                lock = channel.tryLock(0, Long.MAX_VALUE,
                                       true);
            }
            catch (OverlappingFileLockException e) {
                // thrown when an attempt is made to acquire
                // a lock on a a file that overlaps a region
                // already locked by the same JVM or when
                // another thread is already waiting to lock
                // an overlapping region of the same file
                System.out.println(
                    "Overlapping File Lock Error: "
                    + e.getMessage());
            }
            // Checking whether this lock is shared
            boolean isShared = lock.isShared();
            // Releasing the lock
            // using release() method
            lock.release();
            // Closing the channel
            // using standard close() method
            channel.close();
        }
        // Catch block to handle exceptions
        catch (IOException e) {
            // Display message(error) if I/O exception
            // occurs
            System.out.println("I/O Error: "
                               + e.getMessage());
        }
    }
}

输出:

示例 2:

Java


// Java Program to Lock a File before Writing into It
// Importing required classes
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.concurrent.TimeUnit;
// Main class
public class Demo {
    // Main driver method
    public static void main(String[] args) throws Exception
    {
        // Creating object of RandomAccessFile
        RandomAccessFile file
            = new RandomAccessFile("accounts.txt", "rw");
        // Similarly creating object of FileChannel class
        FileChannel channel = file.getChannel();
        // Initially setting lock to file as null
        // as there is no lock by far
        FileLock lock = null;
        // Try block to check for exceptions
        try {
            lock = channel.tryLock();
        }
        // Catch block to handle exceptions
        catch (final OverlappingFileLockException e) {
            // Closing channel and file in order to
            // free up memory resources and avoid leakage
            // using close() method
            file.close();
            channel.close();
        }
        // Writing something while inlocked
        file.writeChars("writing after lock");
        // Making it to sleep for very small amount of time
        TimeUnit.HOURS.sleep(1);
        // Releasig lock over file using release() method
        lock.release();
        // Again closing channel and file in order to
        // free up memory resources and avoid leakage
        // using close() method
        file.close();
        channel.close();
    }
}

输出:

It will throw the OverlappingFileLockException, if a lock that overlaps the requested region is already held by this Java virtual machine, or if another thread is already blocked in this method and is attempting to lock an overlapping region.



相关用法


注:本文由纯净天空筛选整理自praveen13kulkarni大神的英文原创作品 OverlappingFileLockException in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。