如何让Java程序只能启动一次
展开全部
最快的,socket还要用占系统的端口,
其实很简单,java程序启动是,先产生一个.lock的文件,并对此文件加锁,另一个就无法获得锁,听上去很复杂,其实实现很简单。程序如下
private boolean checkLock(){
FileOutputStream fo = null;
File file = new File(".lock");
try {
fo = new FileOutputStream(file);
//加锁,如果程序已经启动就无法获得锁
lock = fo.getChannel().tryLock();
if (lock == null) {
logger.warn("<Warning> <Could not start epayment. this application is still alive.>");
return false;
}else{
return true;
}
} catch (FileNotFoundException e) {
logger.error("checkSftp: lock file can't be created.error:" + e);
return false;
}catch (IOException e) {
logger.error("checkSftp: lock file can't be created.error:" + e);
return false;
}
}
其实很简单,java程序启动是,先产生一个.lock的文件,并对此文件加锁,另一个就无法获得锁,听上去很复杂,其实实现很简单。程序如下
private boolean checkLock(){
FileOutputStream fo = null;
File file = new File(".lock");
try {
fo = new FileOutputStream(file);
//加锁,如果程序已经启动就无法获得锁
lock = fo.getChannel().tryLock();
if (lock == null) {
logger.warn("<Warning> <Could not start epayment. this application is still alive.>");
return false;
}else{
return true;
}
} catch (FileNotFoundException e) {
logger.error("checkSftp: lock file can't be created.error:" + e);
return false;
}catch (IOException e) {
logger.error("checkSftp: lock file can't be created.error:" + e);
return false;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询