Advisory locking using FileLock in java
<p>I have 2 different servers that run the same scheduled java process. That process needs to access a file on a shared file system and lock it. The first process that locks the file has the privilege to do some calculations while the second process just skips the execution.<br>
Here is the code snippet:    </p>

<pre><code>final RandomAccessFile file = new RandomAccessFile("./src/main/resources/test.txt", "rw");
final FileChannel fileChannel = file.getChannel();
final FileLock lock = fileChannel.tryLock();
try
{
    if (lock != null)
    {
        //do some calculations that have nothing to do with the locked file
    }
    else
    {
        //skip the execution
    }
}
finally
{
    if (lock != null)
    {
        lock.release();
    }
    file.close();
}
</code></pre>

<p>What concerns me is that, depending on the OS, the locks can be exclusive or advisory. The documentation says that we should implement the solution as if the lock was advisory to avoid future problems.<br>
My questions are:  </p>

<ol>
<li>Is this code good enough for my purpose even if the lock is advisory?  </li>
<li>Can there happen any race conditions in the code example? Only one of the scheduled processes must run at a time.  </li>
</ol>

<p>Note that I don't need to read/write to the locked file, I just need to lock the file and in that way limit the execution of the processes to 1 process at a time.</p>