最近用到FileLock知识点,对其中的几点做了一些实验发现:
1.这是一个进程之间的锁,对于同一个进程不同的线程你是不能够同时去竞争一把锁的。如下实验:
package springtest.trigger;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Calendar;
import java.util.TimeZone;
public class Demo {
public static int i = 0 ;
private subthread sb = new subthread();
public void init()
{
<span style="color:#ff0000;"> sb.start();
new subthread().start();
</span> }
public static void main(String args[]){
while(true)
{
Demo demo = new Demo();
demo.init();
//这里是为了不要让这个主线程死掉
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class subthread extends Thread{
private RandomAccessFile ra = null ;
private FileChannel channel = null ;
private FileLock fileLock = null ;
public void run()
{
while(true)
{
System.out.println(" doing ");
File file = new File("process.lck");
try {
ra = new RandomAccessFile(file, "rw");
channel = ra.getChannel();
System.out.println("there are going to get lock...");
fileLock = channel.lock(); //这里面得到锁了,且是在线程中得到锁
System.out.println("geted the lock!");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//下面我想要这个地方抛出一个没有抓住的异常
String str=null;
str.charAt(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fileLock != null )
{
try {
fileLock.release();
fileLock = null ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(channel != null)
{
try {
channel.close();
channel = null ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
这上面会报异常的:
doing
doing
Exception in thread "Thread-0" java.nio.channels.OverlappingFileLockException
at sun.nio.ch.FileChannelImpl$SharedFileLockTable.checkList(FileChannelImpl.java:1166)
at sun.nio.ch.FileChannelImpl$SharedFileLockTable.add(FileChannelImpl.java:1068)
at sun.nio.ch.FileChannelImpl.lock(FileChannelImpl.java:824)
at java.nio.channels.FileChannel.lock(FileChannel.java:860)
at springtest.trigger.Demo$subthread.run(Demo.java:89)
there are going to get lock...
geted the lock!
2.多进程间,是可以安然的锁上的。当然如果你在一个进程中的线程中没有释放锁,而此时这个线程由于异常而退出,但是进程没有退出,那么你就会发现这个锁会一直被拿着,而没有释放。所以一定要将锁释放写在finally里面。