2012-11-26 78 views
1

我有一個可執行的jar,它運行一個帶有內部SqlLite數據庫的Java Swing應用程序。 用戶(錯誤)不只是點擊jar,導致數據庫鎖。 我想阻止這種行爲。 我能做什麼? 非常感謝你如何防止在可執行jar上多次點擊

+4

檢查此:http://stackoverflow.com/questions/177189/how-to-implement-a-single-instance-java-application它會給你你正在尋找的代碼。 – Austin

+3

@StefanBe,這個問題的源代碼並不重要 –

回答

0

訪問數據庫的第一個實例應該獲得某種類型的數據庫上的鎖,所有進一步的實例首先應該檢查是否已經有這樣的鎖。如果有 - >「我不是第一個,顯示警告/錯誤,退出」,如果沒有「我是第一個,請鎖定,繼續。」

0

您可以使用JPS或JNI(需要在不同的平臺上實現)。附件是檢查Java應用程序實例的JPS代碼。您可以將其修改爲更多OO。

使用文件,套接字或註冊表作爲鎖並不完美,因爲錯誤操作可能會使您的應用程序無法再啓動(例如,另一個程序佔用相同的端口)很多機會


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(); 

      } 


     } 

}