Posts

Showing posts from February, 2022

How to Implement File Locking Feature in Java

How to implement FileLocking feature in java As we know within the java application we can avoid concurrent writes/read from different threads using synchronization/Locks as shown below. Using synchronized keyword we can make complete method thread safe. Using Lock we can make some portion of the code thread safe. Synchronization.java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Synchronization{ public synchronized void write(){ //write some logic to avoid concurrent writes by different threads. } public void read(){ //some portion of the code Lock lock=new ReentrantLock(true); if(lock.tryLock()){ //some portion of code lock.unlock(); } //some portion of the code } } What if we want to avoid concurrent writes on a file by different applications/processes? java.nio.channels.FileChannel will help us to achieve thi