本博文部分轉載於:http://blog.csdn.net/wangbaochu/article/details/48546717
Java 提供了文件鎖FileLock類,利用這個類可以控制不同程序(JVM)對同一文件的並發訪問,實現進程間文件同步操作。
FileLock是Java 1.4 版本后出現的一個類,它可以通過對一個可寫文件(w)加鎖,保證同時只有一個進程可以拿到文件的鎖,這個進程從而可以對文件做訪問;而其它拿不到鎖的進程要么選擇被掛起等待,要么選擇去做一些其它的事情, 這樣的機制保證了眾進程可以順序訪問該文件。也可以看出,能夠利用文件鎖的這種性質,在一些場景下,雖然我們不需要操作某個文件, 但也可以通過 FileLock 來進行並發控制,保證進程的順序執行,避免數據錯誤。
“Locks are associated with files, not channels. Use locks to coordinate with external processes, not between threads in the same JVM.”
1. 概念
共享鎖: 共享讀操作,但只能一個寫(讀可以同時,但寫不能)。共享鎖防止其他正在運行的程序獲得重復的獨占鎖,但是允許他們獲得重復的共享鎖。
獨占鎖: 只有一個讀或一個寫(讀和寫都不能同時)。獨占鎖防止其他程序獲得任何類型的鎖。
2. FileLock FileChannel.lock(long position, long size, boolean shared)
shared的含義:是否使用共享鎖,一些不支持共享鎖的操作系統,將自動將共享鎖改成排它鎖。可以通過調用isShared()方法來檢測獲得的是什么類型的鎖。
3. lock()和tryLock()的區別:
lock()阻塞的方法,鎖定范圍可以隨着文件的增大而增加。無參lock()默認為獨占鎖;有參lock(0L, Long.MAX_VALUE, true)為共享鎖。
tryLock()非阻塞,當未獲得鎖時,返回null.
4. FileLock的生命周期:在調用FileLock.release(),或者Channel.close(),或者JVM關閉
5. FileLock是線程安全的
6. 注意事項:
同一進程內,在文件鎖沒有被釋放之前,不可以再次獲取。即在release()方法調用前,只能lock()或者tryLock()一次。
文件鎖的效果是與操作系統相關的。一些系統中文件鎖是強制性的,就當Java的某進程獲得文件鎖后,操作系統將保證其它進程無法對文件做操作了。而另一些操作系統的文件鎖是詢問式的(advisory),意思是說要想擁有進程互斥的效果,其它的進程也必須也按照API所規定的那樣來申請或者檢測文件鎖,不然將起不到進程互斥的功能。所以文檔里建議將所有系統都當做是詢問式系統來處理,這樣程序更加安全也更容易移植。
如何避免死鎖:在讀寫關鍵數據時加鎖,操作完成后解鎖;一次性申請所有需要的資源,並且在申請不成功的情況下放棄已申請到的資源。
Java文件鎖定一般都通過FileChannel來實現。主要涉及如下2個方法:
tryLock() throws IOException 試圖獲取對此通道的文件的獨占鎖定。
tryLock(long position, long size, boolean shared) throws IOException 試圖獲取對此通道的文件給定區域的鎖定。
tryLock等同於tryLock(0L, Long.MAX_VALUE, false) ,它獲取的是獨占鎖,所以一定是在釋放鎖之后,才能讀取到文件內容。
1.寫文件的時候加鎖:
Thread_writeFile.java
1 import java.io.File; 2 import java.io.IOException; 3 import java.io.RandomAccessFile; 4 import java.nio.channels.FileChannel; 5 import java.nio.channels.FileLock; 6 import java.util.Calendar; 7 8 public class Thread_writeFile extends Thread{ 9 public void run(){ 10 Calendar calstart=Calendar.getInstance(); 11 File file=new File("D:/test.txt"); 12 try { 13 if(!file.exists()){ 14 file.createNewFile(); 15 } 16 //對該文件加鎖 17 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); 18 FileChannel fileChannel=randomAccessFile.getChannel(); 19 FileLock fileLock=null; 20 while(true){ 21 try { 22 fileLock = fileChannel.tryLock(); 23 break; 24 } catch (Exception e) { 25 System.out.println("有其他線程正在操作該文件,當前線程"+Thread.currentThread().getName()+"休眠1000毫秒"); 26 sleep(1000); 27 } 28 29 } 30 for(int i=1;i<=1000;i++){ 31 sleep(10); 32 StringBuffer sb=new StringBuffer(); 33 sb.append("這是第"+i+"行對應的數據"); 34 sb.append("\n"); 35 randomAccessFile.write(sb.toString().getBytes("utf-8")); 36 } 37 fileLock.release(); 38 fileChannel.close(); 39 randomAccessFile.close(); 40 randomAccessFile=null; 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } catch (InterruptedException e) { 44 e.printStackTrace(); 45 } 46 Calendar calend=Calendar.getInstance(); 47 System.out.println("線程:"+Thread.currentThread().getName()+",寫文件共花了"+(calend.getTimeInMillis()-calstart.getTimeInMillis())+"秒"); 48 } 49 }
測試類:Thread_writeTest
1 public class Thread_writeTest { 2 3 public static void main(String[] args) { 4 Thread_writeFile writeFileThread=new Thread_writeFile(); 5 writeFileThread.setName("writeFileThread"); 6 Thread_writeFile writeFileThread2=new Thread_writeFile(); 7 writeFileThread2.setName("writeFileThread2"); 8 writeFileThread.start(); 9 writeFileThread2.start(); 10 } 11 }
運行結果:
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
有其他線程正在操作該文件,當前線程writeFileThread休眠1000毫秒
線程:writeFileThread2,寫文件共花了10021秒
線程:writeFileThread,寫文件共花了21026秒
2.讀取文件的時候加鎖:
Thread_readFile.java
1 import java.io.File; 2 import java.io.FileNotFoundException; 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.Calendar; 8 9 public class Thread_readFile extends Thread{ 10 public void run(){ 11 try { 12 Calendar calstart=Calendar.getInstance(); 13 sleep(5000); 14 File file=new File("D:/test.txt"); 15 //給該文件加鎖 16 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); 17 FileChannel fileChannel=randomAccessFile.getChannel(); 18 FileLock fileLock=null; 19 while(true){ 20 try { 21 fileLock = fileChannel.tryLock(); 22 break; 23 } catch (Exception e) { 24 System.out.println("有其他線程正在操作該文件,當前線程"+Thread.currentThread().getName()+"休眠1000毫秒"); 25 sleep(1000); 26 } 27 } 28 byte[] buf = new byte[1024]; 29 StringBuffer sb=new StringBuffer(); 30 while((randomAccessFile.read(buf))!=-1){ 31 sb.append(new String(buf,"utf-8")); 32 buf = new byte[1024]; 33 } 34 35 System.out.println(sb.toString()); 36 37 fileLock.release(); 38 fileChannel.close(); 39 randomAccessFile.close(); 40 randomAccessFile=null; 41 42 Calendar calend=Calendar.getInstance(); 43 System.out.println("當前線程:"+Thread.currentThread().getName()+",讀文件共花了"+(calend.getTimeInMillis()-calstart.getTimeInMillis())+"秒"); 44 }catch (FileNotFoundException e) { 45 e.printStackTrace(); 46 } catch (IOException e) { 47 e.printStackTrace(); 48 } catch (InterruptedException e) { 49 e.printStackTrace(); 50 } 51 } 52 }
測試類:Thread_readTest.java
1 public class Thread_readTest { 2 3 public static void main(String[] args) { 4 Thread_readFile readFileThread=new Thread_readFile(); 5 readFileThread.setName("readFileThread"); 6 Thread_readFile writeFileThread2=new Thread_readFile(); 7 writeFileThread2.setName("readFileThread2"); 8 9 readFileThread.start(); 10 writeFileThread2.start(); 11 } 12 }
運行結果:
有其他線程正在操作該文件,當前線程readFileThread休眠1000毫秒
這是第1行對應的數據
這是第2行對應的數據
當前線程:readFileThread2,讀文件共花了5009秒
這是第1行對應的數據
這是第2行對應的數據
當前線程:readFileThread,讀文件共花了6009秒
//================================另外一個例子================================
1 import java.io.FileNotFoundException; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4 import java.io.RandomAccessFile; 5 import java.nio.ByteBuffer; 6 import java.nio.channels.FileChannel; 7 import java.nio.channels.FileLock; 8 import java.util.Date; 9 10 public class FileLockTest { 11 12 public static void main(String[] args){ 13 FileChannel channel = null; 14 FileLock lock = null; 15 try { 16 //1. 對於一個只讀文件通過任意方式加鎖時會報NonWritableChannelException異常 17 //2. 無參lock()默認為獨占鎖,不會報NonReadableChannelException異常,因為獨占就是為了寫 18 //3. 有參lock()為共享鎖,所謂的共享也只能讀共享,寫是獨占的,共享鎖控制的代碼只能是讀操作,當有寫沖突時會報NonWritableChannelException異常 19 channel = new FileOutputStream("test.txt",true).getChannel(); 20 RandomAccessFile raf = new RandomAccessFile("test.txt","rw"); 21 22 //在文件末尾追加內容的處理 23 raf.seek(raf.length()); 24 channel = raf.getChannel(); 25 26 //獲得鎖方法一:lock(),阻塞的方法,當文件鎖不可用時,當前進程會被掛起 27 lock = channel.lock();//無參lock()為獨占鎖 28 //lock = channel.lock(0L, Long.MAX_VALUE, true);//有參lock()為共享鎖,有寫操作會報異常 29 30 //獲得鎖方法二:trylock(),非阻塞的方法,當文件鎖不可用時,tryLock()會得到null值 31 //do { 32 // lock = channel.tryLock(); 33 //} while (null == lock); 34 35 //互斥操作 36 ByteBuffer sendBuffer=ByteBuffer.wrap((new Date()+" 寫入\n").getBytes()); 37 channel.write(sendBuffer); 38 Thread.sleep(5000); 39 } catch (FileNotFoundException e) { 40 e.printStackTrace(); 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } catch (InterruptedException e) { 44 e.printStackTrace(); 45 } finally { 46 if (lock != null) { 47 try { 48 lock.release(); 49 lock = null; 50 } catch (IOException e) { 51 e.printStackTrace(); 52 } 53 } 54 55 if (channel != null) { 56 try { 57 channel.close(); 58 channel = null; 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 } 63 } 64 } 65 }
推薦一個帖子:
https://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible
關於JavaNIO的總結還可以看我的博客: