5 ways to solve Java exclusive file writing

  • 2020-04-01 04:33:22
  • OfStack

This article illustrates 5 ways to solve the problem of Java exclusive file writing.

Plan 1: using RandomAccessFile File operation option s, s means synchronous lock write


RandomAccessFile file = new RandomAccessFile(file, "rws");

Scheme 2: using FileChannel File lock


File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);
FileChannel channel = fis.getChannel();
FileLock fileLock = null;
while(true) {
  fileLock = channel.tryLock(0, Long.MAX_VALUE, false); //True means Shared lock and false means exclusive lock
  if(fileLock!=null) break;
  else  //There are other threads holding the lock
   sleep(1000);
}

Solution 3: Write to a temporary file, then rename the temporary file Buffer + atom Operating principle)


public class MyFile {
  private String fileName;
  public MyFile(String fileName) {
   this.fileName = fileName;
  }
 
  public synchronized void writeData(String data) throws IOException {
   String tmpFileName = UUID.randomUUID().toString()+".tmp";
   File tmpFile = new File(tmpFileName);
   FileWriter fw = new FileWriter(tmpFile);
   fw.write(data);
   fw.flush();
   fw.close();
 
   // now rename temp file to desired name, this operation is atomic operation under most os
   if(!tmpFile.renameTo(fileName) {
     // we may want to retry if move fails
     throw new IOException("Move failed");
   }
  }
}

Solution 4: Encapsulate files by file path and use synchronized Control write file


public class MyFile {
  private String fileName;
  public MyFile(String fileName) {
   this.fileName = fileName;
  } 
  public synchronized void writeData(String data) throws IOException {
   FileWriter fw = new FileWriter(fileName);
   fw.write(data);
   fw.flush();
   fw.close();
  }     
}

Solution 5: I came up with a plan of my own, not very precise. By toggling the read/write control, simulate setting a writable token amount (morphing into a classic read/write problem in the operating system...)


public class MyFile {
  private volatile boolean canWrite = true;
  private String fileName;
  public MyFile(String fileName) {
   this.fileName = fileName;
  }
  public void writeData(String data) {
   while(!canWrite) {
     try { Thread.sleep(100); } catch(InteruptedException ie) { } //You can set a timeout write time
   }
   canWrite = false;
    
   // Now write file
 
   canWrite = true;
  }
}

Above is the Java exclusive write file solution, you have to learn, you can refer to other articles to learn to understand.


Related articles: