来自jdk7的FileLock类的备注,简直看迷了
File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
File-lock objects are safe for use by multiple concurrent threads.
测试代码:
package com.learnFileLock;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class WriteFile implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
File file =new File("D:/test.txt");
FileLock lock= null;
FileChannel channel =null;
RandomAccessFile accessFile=null;
try {
accessFile = new RandomAccessFile(file, "rw");
channel = accessFile.getChannel();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true) {
try {
System.out.println("try get lock thread name is :"+Thread.currentThread().getName());
lock = channel.lock();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("other thread is handling file please wait");
e.printStackTrace();
}
if(lock!=null) {
break;
}
System.out.println("other thread is handling file please wait");
}
for(int i=1;i<=1000;i++){
StringBuffer sb=new StringBuffer();
sb.append("this is line:"+i+",yes thread name:"+Thread.currentThread().getName()+"\n");
try {
accessFile.write(sb.toString().getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
lock.release();
channel.close();
accessFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
File file =new File("D:/test.txt");
try {
if(!file.exists()) {
file.createNewFile();
}
}catch (Exception e) {
// TODO: handle exception
System.out.println("file create fail");
}
System.out.println("---------------------init file is ok");
WriteFile w1 =new WriteFile();
WriteFile w2 = new WriteFile();
Thread thread1= new Thread(w1);
Thread thread2 = new Thread(w2);
thread1.start();
thread2.start();
}
}
结果:FileLock是进程级别锁,不可多次获取
同一进程的
---------------------init file is ok
try get lock thread name is :Thread-0
try get lock thread name is :Thread-1
Exception in thread "Thread-1" java.nio.channels.OverlappingFileLockException
at sun.nio.ch.SharedFileLockTable.checkList(Unknown Source)
at sun.nio.ch.SharedFileLockTable.add(Unknown Source)
at sun.nio.ch.FileChannelImpl.lock(Unknown Source)
at java.nio.channels.FileChannel.lock(Unknown Source)
at com.learnFileLock.WriteFile.run(WriteFile.java:30)
at java.lang.Thread.run(Unknown Source)