我有一个运行带有内部 SqlLite db 的 Java Swing 应用程序的可执行 jar。用户(错误地)不仅仅点击 jar,导致数据库锁定。我想阻止这种行为。我能做些什么?非常感谢您
3 回答
你需要某种同步机制。
您需要自己编写代码,或者您可以为您的应用程序创建一个 Java WebStart 配置,其中 Java WebStart 可以通过单实例服务(您必须在代码中显式调用)处理“仅一次调用”。
You can use JPS or JNI (need to implement on different platform). The attached is the JPS code to check the Java application instance. You can modify it to more OO.
Using File, Socket or Registry as a lock is not perfect, since there are a lot of chance that a mis-operation can make your application can not start any more (for example, another program occupe the same port)
import java.io.*;
public class TestRun {
public TestRun() {}
public static void main(String args[]) {
String jpsApp = "jps -mlvV";
int count = 0;
try {
Process p = Runtime.getRuntime().exec(jpsApp);
//parser the result to check if TestAPP is running
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println();
System.out.println(line);
String[] pair = line.split(" ");
if (pair.length >= 2) {
System.out.println("name is " + pair[1]);
if (pair[1].trim().indexOf("TestRun") > -1) {
count++;
System.out.println("count is " + count);
}
}
}
//it is running, just exit the second instance
if(count>1){
System.out.println("Has run a application!");
return;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
访问数据库的第一个实例应该在数据库上获取某种锁,并且所有进一步的实例应该首先检查是否已经存在这样的锁。如果有 -> “我不是第一个,显示警告/错误,退出。”,如果没有“我是第一个,获取锁,继续。”