Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java file locking on a network

Tags:

People also ask

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.

How do you lock a file for editing in Java?

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 global file locking?

Global file locking is similar to the file locking mechanism that a network-attached storage or file server uses to make sure that only one copy of a file is being edited at the same time. Global file locking takes that concept and applies it to a cloud implementation.

Why is file locking necessary?

Using file locking technology is important when you are sharing a file or document with others. A file lock is used to prevent two people from opening and updating the same document or file at the same time because that would result in one person's updates wiping out the other's.


This is perhaps similar to previous posts, but I want to be specific about the use of locking on a network, rather than locally. I want to write a file to a shared location, so it may well go on a network (certainly a Windows network, maybe Mac). I want to prevent other people from reading any part of this file whilst it it being written. This will not be a highly concurrent process, and the files will be typically less than 10MB.

I've read the FileLock documentation and File documentation and am left somewhat confused, as to what is safe and what is not. I want to lock the entire file, rather than portions of it.

Can I use FileChannel.tryLock(), and it is safe on a network, or does it depend on the type of network? Will it work on a standard Windows network (if there is such a thing).

If this does not work, is the best thing to create a zero byte file or directory as a lock file, and then write out the main file. Why does that File.createNewFile() documentation say don't use this for file locking? I appreciate this is subject to race conditions, and is not ideal.