Principle:
The Filelock in the JDK's NIO package implements a file lock similar to the Linux fcntl , allowing the file to be accessed by the process mutex. With this feature, a powerful Java process mutex can be implemented to ensure that only the unique jar application process is running at the same time at the application level ! avoid certain factors that cause the jar to execute repeatedly, competing with multiple processes, and destroying business data. (Of course, you can do the same thing with Ubuntu-like upstart scripts or ps-p <pid>.)
Realize:
- Package test;
- Import Java.io.File;
- Import java.io.IOException;
- Import Java.io.RandomAccessFile;
- Import Java.nio.channels.FileChannel;
- Import Java.nio.channels.FileLock;
- Import java.util.concurrent.Callable;
- Import Java.util.concurrent.TimeUnit;
- public class Filelocktest {
- public static void Main (string[] args) throws Exception {
- Exclusivewithfilelock (New callable<void> () {
- @Override
- Public Void Call () throws Exception {
- TimeUnit.SECONDS.sleep (10); Simulating business logic with hibernation
- return null;
- }
- });
- }
- public static <V> V Exclusivewithfilelock (callable<v> caller)
- Throws Exception {
- File LockFile = new file ("/tmp/" +filelocktest.class.getcanonicalname ());//Use class name as filename
- if (!lockfile.exists ()) {
- if (!lockfile.getparentfile (). exists ()) {
- Lockfile.getparentfile (). Mkdirs ();
- }
- if (!lockfile.createnewfile ()) {
- throw new IOException ("Create lock File failed!");
- }
- }
- FileChannel FC = null;
- try {
- FC = new Randomaccessfile (lockFile, "RW"). Getchannel ();
- Filelock lck = Fc.trylock ();
- if (lck = = null) {
- System.out.println ("File is lock by another programme");
- System.exit (1);
- } else {
- System.out.println ("Do your ...");
- return Caller.call ();
- }
- } finally {
- if (FC! = null) {
- Fc.close ();
- }
- }
- return null;
- }
- }
Copy Code
Results:
- [Email protected]:~/myworkspace/source/jademo/src$ java test. Filelocktest
- File is lock by another programme
- [Email protected]:~/myworkspace/source/jademo/src$ java test. Filelocktest
- Do your ...
Copy Code
Advantage:
1. Simple to implement and powerful in function.
Java implementation of Java process mutex using Filelock