Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, Is there a way to read a file when that file is locked by other thread?

So i used the following to create a lock on a file so that I can edit it exclusively:

 File file = new File(filename);
 channel = new RandomAccessFile(file, "rw").getChannel();
 lock = channel.tryLock();

Now I have a 2nd thread want to access the same file - just to read, not edit. How do i do that? Right now the 2nd thread will throw an io exception and inform me the file is locked.

Is this doable? Any suggestions? Thanks

like image 677
neo Avatar asked Apr 15 '11 17:04

neo


People also ask

How do you unlock a file in Java?

Verify that the file has not been corrupted and that the file extension matches the format of the file. A reason why would you want to unlock the file is one good way to start the question. The operating system won't permit it. There is nothing you can do about it in Java.

How do you check if a file is locked by another process in Java?

If the file is exclusively locked (by MS Word for example), there will be exception: java. io. FileNotFoundException: <fileName> (The process cannot access the file because it is being used by another process) . This way you do not need to open/close streams just for the check.

What are some of the methods that Java provides to lock files?

In Java, a file lock can be obtained using FileChannel , which provides two methods — lock() and tryLock() — for this purpose. The lock() method acquires an exclusive lock on entire file, whereas the lock(long position, long size, boolean shared) method can be used to acquire a lock on the given region of a ile.

What is file locking in Java?

A token representing a lock on a region of a file. A file-lock object is created each time a lock is acquired on a file via one of the lock or tryLock methods of the FileChannel class, or the lock or tryLock methods of the AsynchronousFileChannel class. A file-lock object is initially valid.


1 Answers

You could try asking for a shared lock using the three argument version of tryLock.

Here is the appropriate javadoc: http://download.oracle.com/javase/1.4.2/docs/api/java/nio/channels/FileChannel.html#tryLock%28long,%20long,%20boolean%29

Basically instead of doing lock=channel.tryLock() you would do lock = channel.trylock(0, Long.MAX_VALUE, true)

As an aside, you should be careful with file locking in java. While you can guarantee the locks behave as expected within the JVM you can't necessarily be sure that they will behave as expected accross multiple processes.

like image 158
Karthik Ramachandran Avatar answered Oct 19 '22 05:10

Karthik Ramachandran