File – Random IT Utensils https://blog.adamfurmanek.pl IT, operating systems, maths, and more. Sat, 02 Jan 2021 19:11:23 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 Concurrency Part 2 – Java file lock https://blog.adamfurmanek.pl/2018/05/05/concurrency-part-2/ https://blog.adamfurmanek.pl/2018/05/05/concurrency-part-2/#comments Sat, 05 May 2018 08:00:15 +0000 https://blog.adamfurmanek.pl/?p=2426 Continue reading Concurrency Part 2 – Java file lock]]>

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.

]]>
https://blog.adamfurmanek.pl/2018/05/05/concurrency-part-2/feed/ 1