---
title: "JAVA文件锁"
author: "vergilwang"
date: "2012-06-07T17:33:00Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2014-02-15T16:12:59Z"
id: 2011377
url: "https://vergilwang.iteye.com/blog/2011377"
---

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

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

代码如下：

锁接口：

Java代码[![收藏代码](http://sosuny.iteye.com/images/icon_star.png)](/admin/blogs/2011377/ "收藏这段代码")

01. packagelock;
02. importjava.io.FileNotFoundException;
03. importjava.io.IOException;
04. publicinterfaceLock{
05. /\**
06. \*检测是否被锁定
07. \*@returntrue被锁定,false空闲
08. \*\*/
09. publicabstractbooleanisLocked()throwsFileNotFoundException;
10. /\**
11. \*获取锁资源
12. \*@returntrue成功锁定目标资源,false锁定操作失败
13. \*\*/
14. publicabstractbooleanobtain()throwsIOException;
15. /\**
16. \*释放锁
17. \*\*/
18. publicabstractvoidunlock();
19. }

 

文件锁的实现：

Java代码[![收藏代码](http://sosuny.iteye.com/images/icon_star.png)](/admin/blogs/2011377/ "收藏这段代码")

001. packagelock;
002. importjava.io.File;
003. importjava.io.FileNotFoundException;
004. importjava.io.IOException;
005. importjava.io.RandomAccessFile;
006. importjava.nio.channels.FileChannel;
007. importjava.nio.channels.FileLock;
008. importjava.nio.channels.OverlappingFileLockException;
009. publicclassFileProgrameLockimplementsLock{
010. privateStringcallerThreadID=null;
011. privateStringlockFileName=null;
012. FileChannelchannel=null;
013. privateFileLocklock=null;
014. publicstaticLockget(StringfileName,StringcallerThreadID){
015. FileProgrameLockd=newFileProgrameLock(fileName);
016. d.callerThreadID=callerThreadID;
017. return(Lock)d;
018. }
019. publicFileProgrameLock(StringlockFileName){
020. this.lockFileName=lockFileName;
021. }
022. /\**
023. \*检测是否被锁定-不建议使用
024. \*@returntrue被锁定,false空闲
025. \*@deprecated
026. \*\*/
027. publicbooleanisLocked()throwsFileNotFoundException{
028. Filetf=newFile(lockFileName);
029. if(!tf.exists()){
030. returnfalse;
031. }
032. FileChannel\_\_channel=newRandomAccessFile(tf,"rw").getChannel();
033. FileLocktl=null;
034. try{
035. tl=\_\_channel.tryLock();
036. if(tl==null){
037. returntrue;
038. }else{
039. returnfalse;
040. }
041. }catch(OverlappingFileLockExceptione){
042. returntrue;
043. }catch(IOExceptione){
044. returntrue;
045. }catch(Exceptione){
046. returntrue;
047. }finally{
048. try{
049. if(tl!=null){
050. tl.release();
051. }
052. tl=null;
053. if(\_\_channel.isOpen()){
054. \_\_channel.close();
055. }
056. \_\_channel=null;
057. tf=null;
058. }catch(IOExceptione){
059. e.printStackTrace();
060. }
061. }
062. }
063. /\**
064. \*获取锁资源
065. \*@returntrue成功锁定目标资源,false锁定操作失败
066. \*\*/
067. publicbooleanobtain()throwsIOException{
068. Filetf=newFile(lockFileName);
069. createFile();
070. channel=newRandomAccessFile(tf,"rw").getChannel();
071. try{
072. //System.out.println("getlock000&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;");
073. lock=channel.lock();
074. //System.out.println("getlock&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;");
075. returntrue;
076. }catch(OverlappingFileLockExceptione){
077. returnfalse;
078. }catch(Exceptione){
079. returnfalse;
080. }
081. }
082. /\**
083. \*释放锁
084. \*\*/
085. publicvoidunlock(){
086. try{
087. if(lock!=null){
088. lock.release();
089. }
090. System.out.println(callerThreadID+"unlockXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
091. if(channel!=null&&channel.isOpen()){
092. channel.close();
093. }
094. lock=null;
095. channel=null;
096. this.deleteFile();
097. }catch(IOExceptione){
098. }
099. }
100. protectedvoidfinalize()throwsThrowable{
101. System.out.println(callerThreadID+this.getClass()+".finalize()");
102. super.finalize();
103. }
104. privatevoidcreateFile()throwsIOException{
105. try{
106. Filetf=newFile(lockFileName);
107. if(!tf.exists()){
108. tf.createNewFile();
109. }
110. tf=null;
111. }catch(IOExceptione){
112. System.out.println(e+lockFileName);
113. throwe;
114. }
115. }
116. privatevoiddeleteFile(){
117. Filetf=newFile(lockFileName);
118. if(tf.exists()){
119. tf.delete();
120. }
121. tf=null;
122. }
123. }

 

工厂类:

 

Java代码[![收藏代码](http://sosuny.iteye.com/images/icon_star.png)](/admin/blogs/2011377/ "收藏这段代码")

01. packagelock;
02. importjava.io.File;
03. importjava.io.FileNotFoundException;
04. importjava.io.IOException;
05. publicclassMakeLockimplementsRunnable{
06. privateStringthreadID="";
07. publicvoidrun(){
08. try{
09. while(true){
10. test2(threadID);
11. Thread.sleep(200);
12. }
13. }catch(IOExceptione){
14. System.out.println(e);
15. e.printStackTrace();
16. }catch(InterruptedExceptione){
17. System.out.println(e);
18. }
19. }
20. publicvoidtest2(StringthreadID)throwsFileNotFoundException,IOException,InterruptedException{
21. Locklock=newMakeLock(threadID).getLock("c:/001/lockfile001.lock",threadID);
22. System.out.println(threadID+":obtain...");
23. booleanb=lock.obtain();
24. //当有重叠时会发生等待，所以外侧先执行isLocked()判断
25. System.out.println(threadID+":obtained"+b);
26. if(b){//执行业务逻辑
27. Thread.sleep(390);
28. for(inti=0;i&lt;Integer.MAX\_VALUE;i++){
29. ;
30. }
31. lock.unlock();
32. }
33. lock=null;
34. }
35. publicMakeLock(StringthreadID){
36. this.threadID=threadID;
37. }
38. publicLockgetLock(Stringname,StringthreadID){
39. finalStringBufferbuf=newStringBuffer();
40. returnFileProgrameLock.get(name,threadID);
41. }
42. }

 

使用方法：

Java代码[![收藏代码](http://sosuny.iteye.com/images/icon_star.png)](/admin/blogs/2011377/ "收藏这段代码")

01. publicvoidtest2(StringthreadID)throwsFileNotFoundException,IOException,InterruptedException{
02. Locklock=newMakeLock(threadID).getLock("c:/001/lockfile001.lock",threadID);
03. if(!lock.isLocked()){
04. System.out.println(threadID+":obtain...");
05. booleanb=lock.obtain();
06. System.out.println(threadID+":obtained"+b);
07. if(b){//执行业务逻辑
08. Thread.sleep(390);
09. for(inti=0;i&lt;Integer.MAX\_VALUE;i++){
10. ;
11. }
12. lock.unlock();
13. }
14. }else{
15. System.out.println(threadID+":can'tgetalock:"+lock);
16. }
17. lock=null;
18. }

 

 

多线程调用测试：

 

Java代码[![收藏代码](http://sosuny.iteye.com/images/icon_star.png)](/admin/blogs/2011377/ "收藏这段代码")

01. publicstaticvoidmain(String\[]args){
02. //newAAA().test();
03. System.out.println("=========================================");
04. Threadth1=newThread(newMakeLock("====================thread1===================="));
05. Threadth2=newThread(newMakeLock("####################thread2####################"));
06. Threadth3=newThread(newMakeLock("@@@@@@@@@@@@@@@@@@@@thread3@@@@@@@@@@@@@@@@@@@@"));
07. Threadth4=newThread(newMakeLock("$$$$$$$$$$$$$$$$$$$$thread4$$$$$$$$$$$$$$$$$$$$"));
08. Threadth5=newThread(newMakeLock("&&&&&&&&&&&&&&&&&&&&thread5&&&&&&&&&&&&&&&&&&&&"));
09. th1.start();
10. th2.start();
11. th3.start();
12. th4.start();
13. th5.start();
14. }

 

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

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

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