Inter-process file locking in java that throws exception

bk kio :

I used FileChannel's tryLock method to obtain a lock on a file from two different java applications, (obviously spawned with 2 different PIDs) , and observed that when a lock is not available, trylock returns null instead of throwing an exception.

As per the javadocs :-

https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#tryLock--

FileChannel's trylock method should throw exception for inter-thread contention, but returns null for inter-process contention. Is there an API where i could get an exception for inter-process contention as well ?

Thanks

Joni :

My guess is, the file lock being owned by another process was considered to be a common case, and not an exceptional situation requiring an exception to be thrown. Lock.tryLock doesn't throw an exception either, it returns false.

If you want to throw an exception in this case, you can do it yourself:

    FileLock fileLock = channel.tryLock();
    if (fileLock == null) {
        throw new IllegalStateException("Lock already held by another process");
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=362030&siteId=1