📜  Java的OverlappingFileLockException 示例

📅  最后修改于: 2022-05-13 01:55:02.370000             🧑  作者: Mango

Java的OverlappingFileLockException 示例

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

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

包视图

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

句法:



public class OverlappingFileLockException
extends IllegalStateException

构造函数总结

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

执行:

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

  1. 创建一个 File 对象来封装要锁定到的文件系统中的实际文件
  2. 创建随机访问文件流(读写)。为此,您必须首先创建一个 RandomAccessFile 对象来封装上面创建的文件对象并打开它进行读写操作。然后使用 RandomAccessFile 对象的 getChannel() API 方法获取文件通道来读取/写入数据
  3. 使用 FileChannel 类的 lock(long, long, boolean) API 方法获取对该频道文件的排他锁。此方法会阻塞,直到可以锁定区域或关闭此通道或调用线程被中断。 boolean 属性将锁标记为共享与否。该方法返回 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());
        }
    }
}


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();
  
        // Iitially 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 memery 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 memery resources and avoid leakage
        // using close() method
        file.close();
        channel.close();
    }
}


输出:

示例 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();
  
        // Iitially 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 memery 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 memery resources and avoid leakage
        // using close() method
        file.close();
        channel.close();
    }
}

输出: