Influenza A virus subtype H5N1 file is 1 of the oldest ways to shop information too percentage information exactly if y'all are working inwards a shared file i.e a file which tin locomote read or write yesteryear multiple readers too writers, y'all require to brand certain that the file is locked before y'all test to write on it. This is needed to ensure that individual doesn't overwrite the information y'all are writing. Fortunately, Java provides a machinery to lock a file before writing using the FileLock interface. You tin learn the grip of FileLock yesteryear using FileChannel for writing to a file. The FileChannel degree is mostly used to write faster inwards the large file too 1 of the mutual agency to write binary information inwards Java.
In gild to lock the file before writing, y'all require to telephone band the tryLock() method on FileChannel. This method attempts to learn an exclusive lock on this channel's file. It returns a lock object representing the newly-acquired lock, or null if the lock could non locomote acquired because roughly other programme holds an overlapping lock.
This is a non-blocking method too an invocation e'er returns immediately, either having acquired a lock on the requested part or having failed to practise so. If it fails to learn a lock because an overlapping lock is held yesteryear roughly other programme too so it returns null.
If it fails to learn a lock for whatever other argue too so an appropriate exception is thrown.
For example, It volition throw the OverlappingFileLockException - If a lock that overlaps the requested part is already held yesteryear this Java virtual machine, or if roughly other thread is already blocked inwards this method too is attempting to lock an overlapping part too ClosedChannelException if this channel is closed.
You require to ensure that those exceptions are handled properly too if y'all are non certain why too how to grip exceptions inwards Java, I advise y'all locomote through the Error too Exception department of Complete Java nine Masterclass course of teaching yesteryear Udemy.
In this program, nosotros convey created a RandomAccessFile called "accounts.txt" too and so retrieved the FileChannel yesteryear calling the getChannel() method on it. In gild to lock the file before writing into it, nosotros convey called the tryLock() method which volition learn the lock.
After acquiring the lock nosotros write roughly characters into the file too before releasing the lock yesteryear calling lock.release() nosotros made our programme to slumber for 1 sixty minutes using TimeUnit.sleep() method. You tin too piece of occupation the Thread.sleep() method hither exactly I prefer TimeUnit because its explicitly on how much fourth dimension thread is going to wait.
This business office is of import to demonstrate what volition occur if roughly other programme is writing into the file at the same time.
When y'all start run this program, it volition practise an accounts.txt file inwards your projection directory too when y'all opened upwardly the file y'all tin run into the content exactly the programme volition non goal it volition locomote along running because of the slumber nosotros convey position there.
Then nosotros test to run the programme in 1 trial to a greater extent than too at this time, y'all volition run into the next error:
Exception inwards thread "main" java.io.IOException: The procedure cannot access the file because roughly 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 programme hasn't released the lock yet. Remember it was paused before calling the lock.release() method.
This becomes to a greater extent than clear amongst the next screenshot from Eclipse IDE, where y'all tin run into that the before programme is notwithstanding running (instance 1) which locked the file too therefore when y'all run the programme again, it died amongst higher upwardly mistake related to file locking:
That's all almost how to lock a file before writing inwards Java. If y'all are non the exclusive author on the file or y'all are working amongst a shared file too so y'all should e'er lock the file before writing information into it. Failing to practise may number inwards file corruption too information loss.
You should too brand certain to unloose the lock in 1 trial y'all are done amongst your writing into the file too render appropriate exception treatment to grab OverlappingFileLockException too IOException.
Other Java too File tutorials y'all may similar to explore
Introduction to Java for Programmers
How to practise 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 nine Masterclass yesteryear Udemy
Thanks for reading this article, if y'all similar my explanation of how to lock a file before writing information into it too so delight percentage amongst your friends too colleagues. If y'all convey whatever questions or feedback too so delight driblet a note.
In gild to lock the file before writing, y'all require to telephone band the tryLock() method on FileChannel. This method attempts to learn an exclusive lock on this channel's file. It returns a lock object representing the newly-acquired lock, or null if the lock could non locomote acquired because roughly other programme holds an overlapping lock.
This is a non-blocking method too an invocation e'er returns immediately, either having acquired a lock on the requested part or having failed to practise so. If it fails to learn a lock because an overlapping lock is held yesteryear roughly other programme too so it returns null.
If it fails to learn a lock for whatever other argue too so an appropriate exception is thrown.
For example, It volition throw the OverlappingFileLockException - If a lock that overlaps the requested part is already held yesteryear this Java virtual machine, or if roughly other thread is already blocked inwards this method too is attempting to lock an overlapping part too ClosedChannelException if this channel is closed.
You require to ensure that those exceptions are handled properly too if y'all are non certain why too how to grip exceptions inwards Java, I advise y'all locomote through the Error too Exception department of Complete Java nine Masterclass course of teaching yesteryear Udemy.
Java Program to lock a file before writing
Now that nosotros empathize that nosotros tin piece of occupation FileChannel's tryLock() method too FileLock interface to lock a file before writing, let's run into the programme inwards action. This volition help y'all 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 later lock"); TimeUnit.HOURS.sleep(1); lock.release(); file.close(); channel.close(); } }
In this program, nosotros convey created a RandomAccessFile called "accounts.txt" too and so retrieved the FileChannel yesteryear calling the getChannel() method on it. In gild to lock the file before writing into it, nosotros convey called the tryLock() method which volition learn the lock.
After acquiring the lock nosotros write roughly characters into the file too before releasing the lock yesteryear calling lock.release() nosotros made our programme to slumber for 1 sixty minutes using TimeUnit.sleep() method. You tin too piece of occupation the Thread.sleep() method hither exactly I prefer TimeUnit because its explicitly on how much fourth dimension thread is going to wait.
This business office is of import to demonstrate what volition occur if roughly other programme is writing into the file at the same time.
When y'all start run this program, it volition practise an accounts.txt file inwards your projection directory too when y'all opened upwardly the file y'all tin run into the content exactly the programme volition non goal it volition locomote along running because of the slumber nosotros convey position there.
Then nosotros test to run the programme in 1 trial to a greater extent than too at this time, y'all volition run into the next error:
Exception inwards thread "main" java.io.IOException: The procedure cannot access the file because roughly 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 programme hasn't released the lock yet. Remember it was paused before calling the lock.release() method.
This becomes to a greater extent than clear amongst the next screenshot from Eclipse IDE, where y'all tin run into that the before programme is notwithstanding running (instance 1) which locked the file too therefore when y'all run the programme again, it died amongst higher upwardly mistake related to file locking:
That's all almost how to lock a file before writing inwards Java. If y'all are non the exclusive author on the file or y'all are working amongst a shared file too so y'all should e'er lock the file before writing information into it. Failing to practise may number inwards file corruption too information loss.
You should too brand certain to unloose the lock in 1 trial y'all are done amongst your writing into the file too render appropriate exception treatment to grab OverlappingFileLockException too IOException.
Other Java too File tutorials y'all may similar to explore
Introduction to Java for Programmers
How to practise 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 nine Masterclass yesteryear Udemy
Thanks for reading this article, if y'all similar my explanation of how to lock a file before writing information into it too so delight percentage amongst your friends too colleagues. If y'all convey whatever questions or feedback too so delight driblet a note.
No comments:
Post a Comment