【Java开源代码栏目提醒】:网学会员Java开源代码为您提供FileLock.java参考,解决您在FileLock.java学习中工作中的难题,参考学习。
import java.io.*;
import java.util.*;
public class FileLock extends Object
{
private boolean locked;
private File file;
private static Hashtable locks;
/*
The getLockForis method gets a file lock for a file. It is synchronized
so that multiple requests will block until the first one is
finished.
*/
public static synchronized
FileLock getLockFor(String path)
{
FileLock retVal = null;
File tmp = new File(path);
String absPath = tmp.getAbsolutePath();
try
{
if(locks == null)
{
locks = new Hashtable();
}
else
{
retVal = (FileLock) locks.get(absPath);
}
if(retVal == null)
{
retVal = new FileLock(tmp);
locks.put(absPath,retVal);
}
}
catch(Exception exp)
{
retVal = null;
}
return retVal;
}
protected FileLock(File f)
{
file = f;
}
public File getFile()
{
return file;
}
//Waits to acquire a lock
public synchronized void lock()
{
while(locked)
{
try
{
wait();
}
catch(Exception exp)
{
}
}
locked = true;
}
//Waits to acquire a lock
//timeout in millis
public synchronized void lock(int timeout)
throws InterruptedException
{
while(locked)
{
wait(timeout);
}
//If wait throws and exception
//we don't get here
locked = true;
}
//Notifies threads waiting for lock
public synchronized void unlock()
{
locked = false;
notifyAll();
}
}