This is the second part of the Concurrency series. For your convenience you can find other parts in the table of contents in Part 1 – Mutex performance in .NET

Today we explore system-wide lock in Java 1.8.0_161 on Windows 10 x64.

There is no built-in mechanism in Java for acquiring system wide lock. One trick is to lock a file — if only every interested process locks the same file, we effectively have a system-wide lock for our processes.

Code

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class Filelock {
    public static void main(String[] args) throws IOException {
        File file = new File("filename");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        while(true){
            long startTime = System.currentTimeMillis();
            for(int i=0;i<100000;++i){
                FileLock lock = channel.lock();
                lock.release();
            }
            long estimatedTime = System.currentTimeMillis() - startTime;
            System.out.println(estimatedTime);
        }
    }
}

As in previous part, nothing magical. Just a lock, measuring time and showing results.

Results

    \[ \begin{array}{cc} Number\ of\ processes & Time [ms] \\ 1 & 320\\ 2 & 641\\ 3 & 1784\\ 4 & 2277\\ 5 & 2897\\ 6 & 3351\\ 7 & 3929\\ 8 & 4541\\ 9 & 5188\\ 10 & 5815\\ \end{array} \]

As we can see, even for one process this lock type is much slower than mutex in previous part.