How To Lock A File Earlier Writing Inwards Java? Example

Influenza A virus subtype H5N1 file is ane of the oldest ways to shop information in addition to portion information only if you lot are working inwards a shared file i.e a file which tin dismiss hold out read or write past times multiple readers in addition to writers, you lot remove to brand certain that the file is locked before you lot show to write on it. This is needed to ensure that soul doesn't overwrite the information you lot are writing. Fortunately, Java provides a machinery to lock a file before writing using the FileLock interface. You tin dismiss larn the handgrip of FileLock past times using FileChannel for writing to a file. The FileChannel degree is to a greater extent than oftentimes than non used to write faster inwards the large file in addition to ane of the mutual agency to write binary information inwards Java.

In fellowship to lock the file before writing, you lot remove to telephone band the tryLock() method on FileChannel. This method attempts to larn an exclusive lock on this channel's file. It returns a lock object representing the newly-acquired lock, or zilch if the lock could non hold out acquired because or so other computer program holds an overlapping lock.

This is a non-blocking method in addition to an invocation e'er returns immediately, either having acquired a lock on the requested part or having failed to exercise so. If it fails to larn a lock because an overlapping lock is held past times or so other computer program so it returns null.

If it fails to larn a lock for whatever other argue so an appropriate exception is thrown.

For example, It volition throw the OverlappingFileLockException - If a lock that overlaps the requested part is already held past times this Java virtual machine, or if or so other thread is already blocked inwards this method in addition to is attempting to lock an overlapping part in addition to ClosedChannelException if this channel is closed.

You remove to ensure that those exceptions are handled properly in addition to if you lot are non certain why in addition to how to handgrip exceptions inwards Java, I advise you lot move through the Error in addition to Exception department of Complete Java ix Masterclass course of written report past times Udemy.



Java Program to lock a file before writing

Now that nosotros empathize that nosotros tin dismiss usage FileChannel's tryLock() method in addition to FileLock interface to lock a file before writing, let's run into the computer program inwards action. This volition help you lot to empathize the concept better.

import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.concurrent.TimeUnit;  /*  * Java Program to lock a file before writing into it.  */  public class Demo {    public static void main(String[] args) throws Exception {          RandomAccessFile file = new RandomAccessFile("accounts.txt", "rw");     FileChannel channel = file.getChannel();          FileLock lock = null;     try {       lock = channel.tryLock();     } catch (final OverlappingFileLockException e) {       file.close();       channel.close();     }      file.writeChars("writing afterward lock");     TimeUnit.HOURS.sleep(1);     lock.release();          file.close();     channel.close();    }  }

In this program, nosotros convey created a RandomAccessFile called "accounts.txt" in addition to so retrieved the FileChannel past times calling the getChannel() method on it. In fellowship to lock the file before writing into it, nosotros convey called the tryLock() method which volition larn the lock.



After acquiring the lock nosotros write or so characters into the file in addition to before releasing the lock past times calling lock.release() nosotros made our computer program to slumber for 1 hr using TimeUnit.sleep() method. You tin dismiss likewise usage the Thread.sleep() method hither only I prefer TimeUnit because its explicitly on how much fourth dimension thread is going to wait.

This purpose is of import to demonstrate what volition occur if or so other computer program is writing into the file at the same time.

When you lot showtime run this program, it volition exercise an accounts.txt file inwards your projection directory in addition to when you lot opened upwards the file you lot tin dismiss run into the content only the computer program volition non destination it volition move along running because of the slumber nosotros convey pose there.

Then nosotros show to run the computer program over again in addition to at this time, you lot volition run into the next error:

Exception inwards thread "main" java.io.IOException: The procedure cannot access the file because or so other procedure has locked a portion of the file
at java.io.RandomAccessFile.writeBytes(Native Method)
at java.io.RandomAccessFile.writeChars(RandomAccessFile.java:1123)
at Demo.main(Demo.java:26)


This happens because the before computer program hasn't released the lock yet. Remember it was paused before calling the lock.release() method.

This becomes to a greater extent than clear alongside the next screenshot from Eclipse IDE, where you lot tin dismiss run into that the before computer program is yet running (instance 1) which locked the file in addition to thus when you lot run the computer program again, it died alongside to a higher house fault related to file locking:

 Influenza A virus subtype H5N1 file is ane of the oldest ways to shop information in addition to portion information only if you lot are working inwards a How to lock a File before writing inwards Java? Example

That's all nigh how to lock a file before writing inwards Java. If you lot are non the exclusive author on the file or you lot are working alongside a shared file so you lot should e'er lock the file before writing information into it. Failing to exercise may effect inwards file corruption in addition to information loss.

You should likewise brand certain to free the lock ane time you lot are done alongside your writing into the file in addition to supply appropriate exception treatment to grab OverlappingFileLockException in addition to IOException.

Other Java in addition to File tutorials you lot may similar to explore
Introduction to Java for Programmers
How to exercise a ZIP file inwards Java?
How to write to a file inwards Java?
How to append text into existing file inwards Java?
How to read from an Excel File inwards Java using Apache POI
How to read a text file into ArrayList inwards Java?
Complete Java ix Masterclass past times Udemy

Thanks for reading this article, if you lot similar my explanation of how to lock a file before writing information into it so delight portion alongside your friends in addition to colleagues. If you lot convey whatever questions or feedback so delight driblet a note.

0 Response to "How To Lock A File Earlier Writing Inwards Java? Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel