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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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
As we can see, even for one process this lock type is much slower than mutex in previous part.