當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。