In Java, is there any way to read the file when it is locked by another thread?

So I use the following command to create a lock on the 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 second thread that wants to access the same file - just for reading, not editing What do I do? Now the second thread will throw an IO exception and notify me that the file is locked

Is this feasible? Any suggestions? thank you

Solution

You can try to use three parameter versions of trylock to request a shared lock

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

Basically not lock = channel Trylock() you can do lock = channel trylock(0,Long.MAX_VALUE,true)

By the way, you should be careful about file locking in Java While you can guarantee that locks work as expected in the JVM, you can't guarantee that they work as expected in multiple processes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>