Java NIO-FileLock

Java NIO는 동시성 및 다중 스레딩을 지원하므로 여러 파일에서 동시에 작동하는 여러 스레드를 처리 할 수 ​​있지만 경우에 따라 파일이 어떤 스레드에서도 공유되지 않고 액세스 할 수 없게됩니다.

이러한 요구 사항에 대해 NIO는 전체 파일 또는 파일 일부에 대한 잠금을 제공하는 데 사용되는 FileLock이라는 API를 다시 제공하므로 파일 또는 그 일부가 공유되거나 액세스되지 않습니다.

이러한 잠금을 제공하거나 적용하려면 두 가지 방법을 제공하는 FileChannel 또는 AsynchronousFileChannel을 사용해야합니다. lock()tryLock()제공되는 잠금 장치는 두 가지 유형이 있습니다.

  • Exclusive Lock − 배타적 잠금은 다른 프로그램이 두 유형의 중복 잠금을 획득하는 것을 방지합니다.

  • Shared Lock − 공유 잠금은 동시에 실행되는 다른 프로그램이 겹치는 배타적 잠금을 획득하는 것을 방지하지만 겹치는 공유 잠금을 획득 할 수 있도록합니다.

파일에 대한 잠금 획득에 사용되는 방법-

  • lock() − FileChannel 또는 AsynchronousFileChannel의이 메소드는 주어진 채널과 관련된 파일에 대해 배타적 잠금을 획득합니다.이 메소드의 반환 유형은 획득 된 잠금을 모니터링하는 데 추가로 사용되는 FileLock입니다.

  • lock(long position, long size, boolean shared) −이 방식 역시 잠금 방식의 오버로드 방식으로 파일의 특정 부분을 잠그는 데 사용됩니다.

  • tryLock() −이 메서드는 잠금을 획득 할 수없고이 채널의 파일에 대해 명시 적으로 배타적 인 잠금을 획득하려고 시도하는 경우 FileLock 또는 null을 반환합니다.

  • tryLock(long position, long size, boolean shared) −이 방법은 배타적이거나 공유 유형일 수있는이 채널 파일의 주어진 영역에 대한 잠금을 획득하려고 시도합니다.

FileLock 클래스의 방법

  • acquiredBy() −이 메서드는 파일 잠금을 획득 한 채널을 반환합니다.

  • position() −이 메서드는 잠긴 영역의 첫 번째 바이트의 파일 내 위치를 반환합니다. 잠긴 영역은 실제 기본 파일 내에 포함되거나 겹칠 필요가 없으므로이 메서드에서 반환 된 값이 파일의 현재 크기를 초과 할 수 있습니다.

  • size() −이 메서드는 잠긴 영역의 크기를 바이트 단위로 반환합니다. 잠긴 영역은 실제 기본 파일 내에 포함되거나 겹칠 필요가 없으므로이 메서드에서 반환 된 값이 파일의 현재 크기를 초과 할 수 있습니다.

  • isShared() −이 방법은 잠금 공유 여부를 결정하는 데 사용됩니다.

  • overlaps(long position,long size) −이 방법은이 잠금이 주어진 잠금 범위와 겹치는 지 여부를 알려줍니다.

  • isValid() −이 메서드는 획득 한 잠금이 유효한지 여부를 알려주며 잠금 객체는 해제되거나 관련 파일 채널이 닫힐 때까지 유효한 상태로 유지됩니다.

  • release()− 획득 한 잠금을 해제합니다. 잠금 개체가 유효하면이 메서드를 호출하면 잠금이 해제되고 개체가 유효하지 않게됩니다. 이 잠금 개체가 유효하지 않은 경우이 메서드를 호출해도 효과가 없습니다.

  • close()−이 메서드는 release () 메서드를 호출합니다. 자동 자원 관리 블록 구성과 함께 사용할 수 있도록 클래스에 추가되었습니다.

파일 잠금을 보여주는 예제입니다.

다음 예제는 파일에 대한 잠금을 만들고 내용을 작성합니다.

package com.java.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileLockExample {
   public static void main(String[] args) throws IOException {
      String input = "Demo text to be written in locked mode.";  
      System.out.println("Input string to the test file is: " + input);  
      ByteBuffer buf = ByteBuffer.wrap(input.getBytes());  
      String fp = "D:file.txt";  
      Path pt = Paths.get(fp);  
      FileChannel channel = FileChannel.open(pt, StandardOpenOption.WRITE,StandardOpenOption.APPEND);  
      channel.position(channel.size() - 1); // position of a cursor at the end of file       
      FileLock lock = channel.lock();   
      System.out.println("The Lock is shared: " + lock.isShared());  
      channel.write(buf);  
      channel.close(); // Releases the Lock  
      System.out.println("Content Writing is complete. Therefore close the channel and release the lock.");  
      PrintFileCreated.print(fp);  
   }  
}
package com.java.nio;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class PrintFileCreated {
   public static void print(String path) throws IOException {  
      FileReader filereader = new FileReader(path);  
      BufferedReader bufferedreader = new BufferedReader(filereader);  
      String tr = bufferedreader.readLine();    
      System.out.println("The Content of testout.txt file is: ");  
      while (tr != null) {      
         System.out.println("    " + tr);  
         tr = bufferedreader.readLine();  
      }  
   filereader.close();  
   bufferedreader.close();  
   }  
}

산출

Input string to the test file is: Demo text to be written in locked mode.
The Lock is shared: false
Content Writing is complete. Therefore close the channel and release the lock.
The Content of testout.txt file is: 
To be or not to be?Demo text to be written in locked mode.