IPB

Welcome Guest ( Log In | Register )



Tags
This content has not been tagged yet
 
Reply to this topicStart new topic

How To Implement Single Instance Application On Java


xico
no avatar
Newbie [Level 1]
*
Group: [HOSTED]
Posts: 14
Joined: 29-July 08
Member No.: 65,644



Post #1 post Jul 29 2008, 04:08 AM
See the next few lines containing Java Code:

CODE
1. // imports
   2. import sun.management.ConnectorAddressLink;  
   3. import sun.jvmstat.monitor.HostIdentifier;  
   4. import sun.jvmstat.monitor.Monitor;  
   5. import sun.jvmstat.monitor.MonitoredHost;  
   6. import sun.jvmstat.monitor.MonitoredVm;  
   7. import sun.jvmstat.monitor.MonitoredVmUtil;  
   8. import sun.jvmstat.monitor.MonitorException;  
   9. import sun.jvmstat.monitor.VmIdentifier;  
  10.  
  11. public static void main(String args[]) {  
  12.         /* The method ManagementFactory.getRuntimeMXBean() returns an identifier with applcation PID
  13.             in the Sun JVM, but each jvm may have you own implementation.
  14.             So in anothers jvm, other than Sun, this code may not work., :(
  15.         */  
  16.         RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();  
  17.         final int runtimePid = Integer.parseInt(rt.getName().substring(0,rt.getName().indexOf("@")));  
  18.                                
  19.         java.awt.EventQueue.invokeLater(new Runnable() {  
  20.             public void run() {  
  21.                  
  22.                 // If exists another instance, show message and terminates the current instance.  
  23.                 // Otherwise starts application.  
  24.                 if (getMonitoredVMs(runtimePid))  
  25.                 {  
  26.                     new MainFrame().setVisible(true);  
  27.                 } else  
  28.                     JOptionPane.showMessageDialog(null,"There is another instance of this application running.");  
  29.                  
  30.             }  
  31.         });  
  32. }


This code above shows us how to implement a single instance application. But let me explain it.

The getMonitoredVMs(int processPid) method receives as paramter the current application PID, and catch the application name that is called from command line, for example, the application was started from c:\java\app\test.jar path, then the value variable is "c:\\java\\app\\teste.jar". This way, we will catch just application name on the line 17 of the code below.
After that, we search JVM for antoher process with the same name, if we found it and the application PID is different, it means that is the second application instance.

CODE
1. private static boolean getMonitoredVMs(int processPid) {  
   2.         MonitoredHost host;  
   3.         Set vms;  
   4.         try {  
   5.             host = MonitoredHost.getMonitoredHost(new HostIdentifier((String)null));  
   6.             vms = host.activeVms();  
   7.         } catch (java.net.URISyntaxException sx) {  
   8.             throw new InternalError(sx.getMessage());  
   9.         } catch (MonitorException mx) {  
  10.             throw new InternalError(mx.getMessage());  
  11.         }  
  12.         MonitoredVm mvm = null;  
  13.         String processName = null;  
  14.         try{  
  15.             mvm = host.getMonitoredVm(new VmIdentifier(String.valueOf(processPid)));  
  16.             processName = MonitoredVmUtil.commandLine(mvm);  
  17.             processName = processName.substring(processName.lastIndexOf("\\") + 1,processName.length());  
  18.             mvm.detach();  
  19.         } catch (Exception ex) {  
  20.              
  21.         }  
  22.        // This line is just to verify the process name. It can be removed.
  23.         JOptionPane.showMessageDialog(null,processName);  
  24.         for (Object vmid: vms) {  
  25.             if (vmid instanceof Integer) {  
  26.                 int pid = ((Integer) vmid).intValue();  
  27.                 String name = vmid.toString(); // default to pid if name not available  
  28.                 try {  
  29.                      mvm = host.getMonitoredVm(new VmIdentifier(name));  
  30.                      // use the command line as the display name  
  31.                      name =  MonitoredVmUtil.commandLine(mvm);  
  32.                      name = name.substring(name.lastIndexOf("\\")+1,name.length());  
  33.                      mvm.detach();  
  34.                      if ((name.equalsIgnoreCase(processName)) && (processPid != pid))  
  35.                          return false;  
  36.                 } catch (Exception x) {  
  37.                      // ignore  
  38.                 }  
  39.             }  
  40.         }  
  41.          
  42.         return true;  
  43. }

The problem of all this code are the imports, that are defined only in the file tools.jar file and has a size of 11MB. But to solve this problem, I have unpacked this file and a packed a new file called VM.ZIP only with the necessary classes, and it has a size of just 81kb.

PS: When you're debbuging the code, the processName variable will be assigned to Class Main project, for example, the name of its class is Principal and is in the package com.main, then the variable processName will be assigned as "com.main.Principal." To test you have to open another instance of Debug and it will work.
In the release case, it will be showed the application name as we can see in the line code JOptionPane.showMessageDialog(null,processName).


Below the file attached VM.zip.
Attached File  VM.zip ( 80.31K ) Number of downloads: 12
Go to the top of the page
+Quote Post

Reply to this topicStart new topic

Collapse

> Similar Topics

    Topic Title Replies Topic Starter Views Last Action
No new   72 ultrasmad 7,314 15th February 2008 - 12:10 PM
Last post by: avara.badal
No New Posts   5 ultrasmad 712 10th October 2004 - 01:46 PM
Last post by: eldeo
No New Posts 1 muskrat 262 15th July 2006 - 05:23 PM
Last post by: BuffaloHELP
No New Posts   1 Jasontian 171 8th December 2007 - 03:59 AM
Last post by: jlhaslip
No New Posts 3 pasten 113 6th October 2008 - 01:26 PM
Last post by: creatative
No New Posts   1 Seth teh ROM masta 78 15th August 2008 - 08:00 AM
Last post by: truefusion
No New Posts   1 myshop 149 10th February 2007 - 05:53 PM
Last post by: serverph
No New Posts   1 technischburo 61 26th June 2008 - 12:25 AM
Last post by: jlhaslip
No New Posts   1 dogtag 298 12th June 2007 - 07:32 PM
Last post by: truefusion
No New Posts   1 jsyzfyj 210 24th November 2007 - 02:20 PM
Last post by: rvalkass


 



RSS Lo-Fi Version Time is now: 3rd December 2008 - 11:43 PM