Java implementation of Java process mutex using Filelock

Source: Internet
Author: User
Tags mutex

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:

  1. Package test;
  2. Import Java.io.File;
  3. Import java.io.IOException;
  4. Import Java.io.RandomAccessFile;
  5. Import Java.nio.channels.FileChannel;
  6. Import Java.nio.channels.FileLock;
  7. Import java.util.concurrent.Callable;
  8. Import Java.util.concurrent.TimeUnit;
  9. public class Filelocktest {
  10. public static void Main (string[] args) throws Exception {
  11. Exclusivewithfilelock (New callable<void> () {
  12. @Override
  13. Public Void Call () throws Exception {
  14. TimeUnit.SECONDS.sleep (10); Simulating business logic with hibernation
  15. return null;
  16. }
  17. });
  18. }
  19. public static <V> V Exclusivewithfilelock (callable<v> caller)
  20. Throws Exception {
  21. File LockFile = new file ("/tmp/" +filelocktest.class.getcanonicalname ());//Use class name as filename
  22. if (!lockfile.exists ()) {
  23. if (!lockfile.getparentfile (). exists ()) {
  24. Lockfile.getparentfile (). Mkdirs ();
  25. }
  26. if (!lockfile.createnewfile ()) {
  27. throw new IOException ("Create lock File failed!");
  28. }
  29. }
  30. FileChannel FC = null;
  31. try {
  32. FC = new Randomaccessfile (lockFile, "RW"). Getchannel ();
  33. Filelock lck = Fc.trylock ();
  34. if (lck = = null) {
  35. System.out.println ("File is lock by another programme");
  36. System.exit (1);
  37. } else {
  38. System.out.println ("Do your ...");
  39. return Caller.call ();
  40. }
  41. } finally {
  42. if (FC! = null) {
  43. Fc.close ();
  44. }
  45. }
  46. return null;
  47. }
  48. }

Copy Code

Results:

    1. [Email protected]:~/myworkspace/source/jademo/src$ java test. Filelocktest
    2. File is lock by another programme
    3. [Email protected]:~/myworkspace/source/jademo/src$ java test. Filelocktest
    4. Do your ...

Copy Code

Advantage:
1. Simple to implement and powerful in function.

Java implementation of Java process mutex using Filelock

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.