Eseguire un file lock in Java

Mattepuffo's logo
Eseguire un file lock in Java

Eseguire un file lock in Java

Ci sono varie motivazioni per voler eseguire un file lock, come ad esempio evitare che qualcuno scriva su un file che stiamo leggendo.

Oppure per evitare di eseguire operazioni sullo stesso file in ambito multi-thread.

Oggi vediamo come eseguire questa operazione in Java; il tutto avviene tramite la classe FileChannel che ha disposizione due metodi, che ritornano entrambi un FileLock:

  • lock() --> acquisisce un lock esclusivo su tutto il file
  • lock(long position, long size, boolean shared) --> acquisisce un lock esclusivo su una porzione del file
  • tryLock() --> tenta di acquisire un lock esclusivo su tutto il file
  • tryLock(long position, long size, boolean shared) --> acquisisce un lock esclusivo su una porzione del file

Noi useremo il secondo su tutto il file, passando true come ultimo parametro; cosi il file deve essere aperto in sola lettura, e solo possibilmente anche in scrittura.

Ecco un esempio:

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 Main {

    public static void main(String[] args) {
        try {
            String strFile = "/home/matte/Desktop/test.txt";
            Path path = Paths.get(strFile);
            try (FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ)) {
                FileLock fileLock = fileChannel.lock(0, Long.MAX_VALUE, true);
                System.out.println("LOCK ACQUISITO:" + fileLock.isValid());
                System.out.println("LOCK DI TIPO SHARED:" + fileLock.isShared());
                ByteBuffer buffer = ByteBuffer.allocate(30);
                int readed = fileChannel.read(buffer);
                while (readed != -1) {
                    buffer.flip();
                    while (buffer.hasRemaining()) {
                        System.out.print((char) buffer.get());
                    }
                    buffer.clear();
                    Thread.sleep(1000);
                    readed = fileChannel.read(buffer);
                }
            }
            System.out.print("Chiudiamo il canale --> rilascia anche il lock");
        } catch (IOException | InterruptedException ex) {
            System.out.println(ex.getMessage());
        }
    }

}

Questo è l'output:

LOCK ACQUISITO:true
LOCK DI TIPO SHARED:true
Questo è il contenuto del file locked!

Quello che vi conviene fare è "giocare" con i quattro metodo e fare un pò di tentativi tra leggere e scrivere.

Enjoy!


Condividi

Commentami!