利用FileLock 限制同一实例打开多次 多开

 

是用类名作为filelock 限制同一个类的实例 每当打开一个实例的时候 对该file加lock

	public static boolean isAppRunning(Object obj)
	{
		File f = new File(obj.getClass().getName()+".lock");
		FileChannel channel = null;
		FileLock lock = null;

		try
		{
			try
			{
				channel = new RandomAccessFile(f, "rw").getChannel();
				lock = channel.tryLock();
			}
			catch (OverlappingFileLockException e)
			{
				closeLock(channel,lock,null);
				return true;
			}
			if (lock == null)
			{
				closeLock(channel,lock,null);
				return true;
			}
			Runtime.getRuntime().addShutdownHook(new ShutDownTask(f, channel, lock));
			return false;
		}
		catch (Exception e)
		{
			closeLock(channel,lock,null);
			return true;
		}
	}

 

	protected static void closeLock(FileChannel channel,FileLock lock,File file)
	{
		try
		{
			lock.release();
			channel.close();
			if(file!=null)
				file.delete();
		}
		catch (Exception e)
		{}
	}

jvm退出时执行的任务

class ShutDownTask extends Thread
{
	File f = null;
	FileChannel channel = null;
	FileLock lock = null;

	public ShutDownTask(File f, FileChannel channel, FileLock lock)
	{
		super();
		this.f = f;
		this.channel = channel;
		this.lock = lock;
	}

	@Override
	public void run()
	{
		closeLock(channel, lock, f);	
	}
}




 

你可能感兴趣的:(J2SE,file,exception,null,thread,object,jvm)