Last active
March 10, 2025 19:14
-
-
Save aerodame/e6ab11c9790c13eca3481e4e86290673 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.IOException; | |
import java.io.RandomAccessFile; | |
import java.nio.channels.FileChannel; | |
import java.nio.channels.FileLock; | |
import java.nio.channels.OverlappingFileLockException; | |
public class FileLockingExample { | |
public static void main(String[] args) { | |
File file = new File("locked_file.txt"); | |
try { | |
file.createNewFile(); | |
} catch (IOException e) { | |
System.err.println("Error creating file: " + e.getMessage()); | |
return; | |
} | |
try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); | |
FileChannel channel = randomAccessFile.getChannel()) { | |
System.out.println("Attempting to acquire lock on: " + file.getAbsolutePath()); | |
FileLock lock = null; | |
try { | |
lock = channel.lock(); // This line attempts to acquire the lock. | |
if (lock != null) { | |
System.out.println("Lock acquired!\n Performing ops on the locked file..."); | |
Thread.sleep(5000); // Simulate some work. | |
System.out.println("Finished file operations."); | |
} | |
} catch (OverlappingFileLockException e) { | |
System.err.println("File is already locked by another process or thread."); | |
} catch (IOException | InterruptedException e) { | |
System.err.println("Error during lock operation: " + e.getMessage()); | |
} finally { | |
if(lock != null) { | |
System.out.println("Attempting to release Lock."); | |
lock.release(); | |
System.out.println("Lock released."); | |
} | |
} | |
} catch (IOException e) { | |
System.err.println("Error accessing file: " + e.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment