JAVA文件锁

项目使用到集群环境,流程发送时如果确保一个流程不会被两个流程同时调用?

有一种办法是用文件锁的方式来实现。

代码如下:

锁接口:

Java代码   收藏代码
  1. package lock;  
  2.   
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5.   
  6. public interface Lock {  
  7.   
  8.     /** 
  9.      * 检测是否被锁定 
  10.      * @return true被锁定 ,false空闲 
  11.      * */  
  12.     public abstract boolean isLocked() throws FileNotFoundException;  
  13.   
  14.     /** 
  15.      * 获取锁资源 
  16.      * @return true成功锁定目标资源 ,false锁定操作失败 
  17.      * */  
  18.     public abstract boolean obtain() throws IOException;  
  19.   
  20.     /** 
  21.      * 释放锁 
  22.      * */  
  23.     public abstract void unlock();  
  24.   
  25. }  
 

 

文件锁的实现:

Java代码   收藏代码
  1. package lock;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6. import java.io.RandomAccessFile;  
  7. import java.nio.channels.FileChannel;  
  8. import java.nio.channels.FileLock;  
  9. import java.nio.channels.OverlappingFileLockException;  
  10.   
  11. public class FileProgrameLock implements Lock{  
  12.     private String callerThreadID = null;  
  13.     private String lockFileName = null;  
  14.     FileChannel channel = null;  
  15.     private FileLock lock = null;  
  16.       
  17.     public static Lock get(String fileName,String callerThreadID){  
  18.         FileProgrameLock d = new FileProgrameLock(fileName);  
  19.         d.callerThreadID = callerThreadID;  
  20.         return (Lock)d;  
  21.     }  
  22.       
  23.     public FileProgrameLock(String lockFileName){  
  24.         this.lockFileName = lockFileName;  
  25.     }  
  26.       
  27.     /** 
  28.      * 检测是否被锁定-不建议使用 
  29.      * @return true被锁定 ,false空闲 
  30.      * @deprecated  
  31.      * */  
  32.     public boolean isLocked() throws FileNotFoundException {  
  33.         File tf = new File(lockFileName);  
  34.         if( ! tf.exists()){  
  35.             return false;  
  36.         }  
  37.         FileChannel __channel = new RandomAccessFile(tf, "rw").getChannel();  
  38.         FileLock tl = null;  
  39.         try {  
  40.             tl = __channel.tryLock();  
  41.             if (tl == null) {  
  42.                 return true;  
  43.             } else {  
  44.                   
  45.                 return false;  
  46.             }  
  47.         } catch (OverlappingFileLockException e) {  
  48.             return true;  
  49.         } catch (IOException e) {  
  50.             return true;  
  51.         }catch (Exception e) {  
  52.             return true;  
  53.         }finally{  
  54.             try {  
  55.                 if(tl != null){  
  56.                     tl.release();  
  57.                 }  
  58.                 tl = null;  
  59.                 if(__channel.isOpen()){  
  60.                     __channel.close();  
  61.                 }  
  62.                 __channel = null;  
  63.                 tf = null;  
  64.             } catch (IOException e) {  
  65.                 e.printStackTrace();  
  66.             }  
  67.               
  68.         }  
  69.     }  
  70.   
  71.     /** 
  72.      * 获取锁资源 
  73.      * @return true成功锁定目标资源 ,false锁定操作失败 
  74.      * */  
  75.     public boolean obtain() throws IOException {  
  76.         File tf = new File(lockFileName);  
  77.         createFile();  
  78.         channel = new RandomAccessFile(tf, "rw").getChannel();  
  79.         try {  
  80. //          System.out.println("get lock 000 >>>>>>>>>>>>>>>");  
  81.             lock = channel.lock();  
  82. //          System.out.println("get lock >>>>>>>>>>>>>>>");  
  83.             return true;  
  84.         } catch (OverlappingFileLockException e) {  
  85.             return false;  
  86.         }catch (Exception e) {  
  87.             return false;  
  88.         }  
  89.     }  
  90.   
  91.     /** 
  92.      * 释放锁 
  93.      * */  
  94.     public void unlock() {  
  95.         try {  
  96.             if(lock != null){  
  97.                 lock.release();  
  98.             }  
  99.             System.out.println(callerThreadID + " unlock XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ");  
  100.             if(channel != null && channel.isOpen()){  
  101.                 channel.close();  
  102.             }  
  103.             lock = null;  
  104.             channel = null;  
  105.             this.deleteFile();  
  106.         } catch (IOException e) {  
  107.         }  
  108.     }  
  109.       
  110.     protected void finalize() throws Throwable {  
  111.         System.out.println(callerThreadID + this.getClass() + " .finalize()");  
  112.         super.finalize();  
  113.     }  
  114.       
  115.     private void createFile() throws IOException{  
  116.         try{  
  117.             File tf = new File(lockFileName);  
  118.             if(! tf.exists()){  
  119.                 tf.createNewFile();  
  120.             }  
  121.             tf = null;  
  122.         }catch(IOException e){  
  123.             System.out.println(e+lockFileName);  
  124.             throw e;  
  125.         }  
  126.     }  
  127.       
  128.     private void deleteFile(){  
  129.         File tf = new File(lockFileName);  
  130.         if(tf.exists()){  
  131.             tf.delete();  
  132.         }  
  133.         tf = null;  
  134.     }  
  135. }  

 

工厂类:

 

Java代码   收藏代码
  1. package lock;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6.   
  7. public class MakeLock implements Runnable{  
  8.     private String threadID = "";  
  9.     public void run() {  
  10.         try {  
  11.             while(true) {  
  12.                 test2(threadID);  
  13.                 Thread.sleep(200);  
  14.             }  
  15.         } catch (IOException e) {  
  16.             System.out.println(e);  
  17.             e.printStackTrace();  
  18.         } catch (InterruptedException e) {  
  19.             System.out.println(e);  
  20.         }  
  21.     }  
  22.       
  23.     public void test2(String threadID) throws FileNotFoundException, IOException, InterruptedException{  
  24.         Lock lock = new MakeLock(threadID).getLock("c:/001/lockfile001.lock",threadID);  
  25.             System.out.println(threadID+":obtain...");  
  26.             boolean b = lock.obtain();  
  27. //当有重叠时会发生等待,所以外侧先执行isLocked()判断  
  28.  System.out.println(threadID+":obtained   "+b);  
  29.             if(b){//执行业务逻辑  
  30.                 Thread.sleep(390);  
  31.                 for(int i = 0 ; i < Integer.MAX_VALUE ; i ++){  
  32.                     ;  
  33.                 }  
  34.                 lock.unlock();  
  35.             }  
  36.         lock = null;  
  37.               
  38.     }  
  39.       
  40.     public MakeLock(String threadID){  
  41.         this.threadID = threadID;  
  42.     }  
  43.       
  44.     public Lock getLock(String name,String threadID) {  
  45.         final StringBuffer buf = new StringBuffer();  
  46.         return FileProgrameLock.get(name,threadID);  
  47.     }  
  48.       
  49. }  
 

 

 使用方法:

Java代码   收藏代码
  1. public void test2(String threadID) throws FileNotFoundException, IOException, InterruptedException{  
  2.         Lock lock = new MakeLock(threadID).getLock("c:/001/lockfile001.lock",threadID);  
  3.         if (!lock.isLocked()) {  
  4.             System.out.println(threadID+":obtain...");  
  5.             boolean b = lock.obtain();  
  6.             System.out.println(threadID+":obtained   "+b);  
  7.             if(b){//执行业务逻辑  
  8.                 Thread.sleep(390);  
  9.                 for(int i = 0 ; i < Integer.MAX_VALUE ; i ++){  
  10.                     ;  
  11.                 }  
  12.                 lock.unlock();  
  13.             }  
  14.         }else{  
  15.             System.out.println(threadID+":can't get a lock :"+lock);  
  16.         }  
  17.         lock = null;  
  18.               
  19.     }  
 

 

 

多线程调用测试:

 

Java代码   收藏代码
  1. public static void main(String[] args) {  
  2.         //new AAA().test();  
  3.         System.out.println("=========================================");  
  4.         Thread th1 = new Thread(new MakeLock("==================== thread1 ===================="));  
  5.         Thread th2 = new Thread(new MakeLock("#################### thread2 ####################"));  
  6.         Thread th3 = new Thread(new MakeLock("@@@@@@@@@@@@@@@@@@@@ thread3 @@@@@@@@@@@@@@@@@@@@"));  
  7.         Thread th4 = new Thread(new MakeLock("$$$$$$$$$$$$$$$$$$$$ thread4 $$$$$$$$$$$$$$$$$$$$"));  
  8.         Thread th5 = new Thread(new MakeLock("&&&&&&&&&&&&&&&&&&&& thread5 &&&&&&&&&&&&&&&&&&&&"));  
  9.         th1.start();  
  10.         th2.start();  
  11.         th3.start();  
  12.         th4.start();  
  13.         th5.start();  
  14.     }  
 

 

=================

经测试可以在共享文件系统下工作。

附件中AAA.java多线程测试代码可以直接运行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值