xico
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. [attachment=1223:VM.zip]
Comment/Reply (w/o sign-up)
prashant144
Feb 26 2009, 06:32 AM
Hi, Its very nice yar. I also want the same thing but i use some different technique. 1. I make a ServerSocket object and capture a port say 1111 If again on another instance you are trying to make a same object then it is giving you error because your 1111 port is captured by 1st instance. So easily you can track and throw a error to user. Its very simple and effective too. Just follow the link for all codes. Single instance aaplicaion in JAVA2. Another method is make a txt file with one instance and delete while exiting. On next time just check if file is existing then any instance is running. And you can track the error. For being effective do not create file in C partition.
Comment/Reply (w/o sign-up)
zakaluka
Apr 10 2009, 07:42 AM
I've used the lock method described by Prashant. The only problem is that the file has to be deleted manually if the application crashes without removing the lock. The benefit is that this technique works on every operating system and platform, with any java toolkit. I had a problem with capturing certain ports on unix, especially with certain firewalls running in the background. Regards, z.
Comment/Reply (w/o sign-up)
prashant144
May 11 2009, 01:58 PM
Hi Zakuluka, I am not tested in unix. If you have problem in capturing port then just make unique port like 99999 something like that which nobody use. thanks QUOTE (zakaluka @ Apr 10 2009, 08:42 AM)  I've used the lock method described by Prashant. The only problem is that the file has to be deleted manually if the application crashes without removing the lock.
The benefit is that this technique works on every operating system and platform, with any java toolkit. I had a problem with capturing certain ports on unix, especially with certain firewalls running in the background.
Regards,
z.
Comment/Reply (w/o sign-up)
nanaji
Sep 16 2009, 07:52 AM
QUOTE (xico @ Jul 29 2008, 05: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. [attachment=1223:VM.zip] Great work Thanks Nanaji
Comment/Reply (w/o sign-up)
nooc9
Sep 17 2009, 04:40 PM
For web applications there is a jnlp method of doing it. Check out javax.jnlp.SingleInstanceService found in jnlp.jar, included in the sdk.
Comment/Reply (w/o sign-up)
Similar Topics
Keywords : implement, single, instance, application, java
- Java And Jsp On Trap 17
Java and jsp on trap 17 (2)
Java Script To Hide The Url In Address Bar
Does any one know about this ? (8) Hello friends , just now i came accross a particular type of script which is capable of masking the
URL which is seen in the Address bar of the webpage , that is by implementing the particular Java
Script when the user visits a page eg. www.mysite.com , then it is possible for the admin of
www.mysite.com to mask this site and display some other website in the viewers address bar. I came
to know that such a script can be written using Java Scripts , Can any one get me the Script ??....
Which Is Good Java Or Dot Net
which is good (13) Hi, I want to know which is going to be a success in future. I've asked this question to
many but all are giving my vague answers. I'm asking this question because i'm going to join
a company where i can choose either dot net or java. Which one should i choose. Wax....
How To Implement A Date Picker On A Web Page
(2) Some pages may need users to input date values. It would be nice if the users just need to click and
pick and done. This way we may also eliminate the possible input errors. Below is the code I used to
implement this. You may want to save it as datepicker.js for other web pages to use. I also attached
3 files for you to download. All you need to do is unzip the 3 files to a directory under any web
server and start trying it. If you are using jsp, you can refer to the submited field by adding
something like request.getParameter("date1") to your page. If you're using....
Java And Xml: Links You Must Have
(1) XML and JavaGeneral XML resources * "XML, Java and the Future of the Web," Jon Bosak. The
paper that started it all, at least from a Java programmer's point of view. Definitely worth a
read, even if it's a bit dated. Jon is commonly considered to be the father of XML. Funny how
all of these technologies seem to have paternity
http://metalab.unc.edu/pub/sun-info/standa...hy/xmlapps.html * "Media-Independent
PublishingFour Myths about XML" Jon Bosak
http://metalab.unc.edu/pub/sun-info/standa.../why/4myths.htm * Robin Cover's XML-....
Java Multithreading Issues
(2) So we have a web based application running on JBoss on several clustered servers. The front end of
the application is using jms to communicate with the middleware MDB, which communicates with other
backend application servers. The application runs well when only a few requests are submited.
However, when requests boost to couple thousands, the app starts to crash. The log files shows a
concurrency issue with the ThreadPoolExecutor. When we set the core size pool to one the issue was
solved. Looks like we have concurrent issue of multiple threads accessing same resource s....
Call Pdf995 From Java
(0) How can i call pdf995 engine from Java to generate Pdf from Doc. This approach from Visual Basic
Application is provided in http://www.pdf995.com/faq_dev.html . How can i approach same from Java?
Can anyone help? ....
Hosting Struts Application
I need help here (1) I just got web hosting approved and I want to host the site I created using Struts framework.
I'm a complete newb when it comes to web hosting, so I need a little help. Is there a tutorial
that covers this subject? Any help with hosting of Java applications will be appreciated.....
Learn Java Programming Language Online Step By Step
(1) I had found this site >> http://learnjava.awardspace.com This website is for people who want
to learn Java Programming Language step by step. This website also includes JAVA lessons from the
beginning to advanced level. So this site appropriates for the beginner of Java programmer language
or non-basic Java Programming Language. The lessons are easy to follow and understand starting
from how to get your PC JAVA ready, the fundamental programming concept and creating the real
application. Moreover, the working examples are also included. Please enjoy the les....
Java Or C++
(19) Many having tell me to make my MMORPG in java leads me to agree, But I'm not sure truly is it
not yet easier, but yet the outcome of programming an MMORPG in java will make it fail or succeed
more then one in C+= I've learned a lot of variables in javascript, and I don't think that
java would be too bad either. My true question is, is those who use these languages, which seems
to give better outcome, and which seems to be more in ease. Regards -PCessna....
Java Applet Query
(2) Hey there, I have made an applet that shows images moving about the screen. I have pause/resume
buttons that work. But i've noticed that when the applet is interuppted by something i.e moving
another window over it, it will automatically repaint. My question is how can I stop this? How can
I make it so that the only time that paint is called is when I want it to be called? Thanks in
advance!....
Java Iterator Help
I need help with a method using iterator (3) /** * Remove from the club's collection all members who * joined in the given month,
and return them stored * in a sparate collection object. * @param month The month of the
membership. * @param year The year of the membership. * @return The number of members.
*/ public ArrayList purge(int month, int year) { if(month >= 1 && month
{ Iterator it = members.iterator(); ArrayList purged;
purged = new ArrayList(); int counter = 0; wh....
Helpful Registry Edit For Java Programmers
Command Prompt on right click menu (3) With this registry edit you can easily open the current folder in prompt without going through any
Change Directory commands (cd). This is useful for people like me who are programming in JAVA, and
every time to create class files and test them I have a diificult time just entering the commands in
Prompt. But if you don't want to use this registry edit you can create the directory in C:\
drive like C:\files so you have to navigate very little in prompt. If you are experienced in
regedit you can do it yourself shown below OR download the attachment and apply it. I t....
Jsp Or Java Chat Script Like Mig33
(5) so most of you guys know mig33. its a wap application,probaly java.most kindly to be java. does
anyone have java knowlege or knows where i can get a chat script like mig33? i also know this server
supports jsp so im planing to use it for my application. i was hosted here last year but moved
because i found a better host. now im back just to use the jsp on this server. Im planing to run
chat applictions so if any one wants to help me in my project let me know.....
Best Java Framework For J2ee?
Your Opinion About The Best Java Framework (11) What is the best framework to make enterprise application using Java (J2EE)? Currently I am
learning Spring and it is quite good eventhough it is very complicated in my opinion. Maybe someone
can share which framework that you use What are its advantages and disadvantages? I seek a J2EE
framework that supports JMS and offer quick development process.....
What's The Relationship Between Javascript And Java
are they the same or different (7) I think most of you always confuse about java and javascript .So I make this topic to talk about it.
Javascript and Java ,they have the same first four letter. Java and Javascript is the two language
is very popular in the web world.Java is the general-purpose programming language that you can
create an application or an applet.Javascript is a script language that looks sort of like java;with
it you can do various nifty things in web pages.They are independent languages ,used for different
purposes.If you are interesting in creating a website you should learn how to w....
Java Helpdesk
All your queries regarding Java Programming goes here. (10) Hellow friends, I am creating this thread for all queries and suggestions related to java coding. If
you face any problem, post it here, and others who have a solution can post the reply here. Hope it
helps the users.....
Is It Possible To Make A Splash Screen In Java?
(6) (A splash screen is an image that pops up before you run a program, sometimes it tells you what
portion of the program is being loaded. One example that immediately comes to mind is Ad-Aware,
which you should probably get if you don't have it.) Is there anything that could do this in
Java? I thought about having just a JFrame with the top bar and edges hidden, but I found nothing in
the API that suggests that that's possible.....
Java Basic Program Guidance
(7) aving some problems taking in the Java at Uni, Was wondering if anyone could shine some light on it
for me. My task is to write a program that will ask you to enter 2 words. the program will then
print out both words on one line. However the words will be seperated by dots that will make the
total length of the line 40. so if your first word was turtle and the second was abc, the output
would be turtle...............................abc The program should check for certain conditions:
1. a word can not be longer than 37 characters; 2. there must always be atlest 2 do....
Java Web Start Jnlp And Mysql
(3) I think I have nearly managed to create a JNLP file and get my application running successfully.
Unfortunately I am having a problem connecting to a MySQL database when using Java Webstart, the
error that I get is shown below which incidently works fine when I run the app from eclipse. Has
anyone successfully managed to connect to MySQL using Java Web Start, if so could you please explain
why the regular doesn't work in more detail or perhaps post an example of simple connection java
file so I can edit it so it works with what I have already developed. Thanks in ad....
How To Create Java Button Or Frame
to be customized (17) hi to all!!!! just like to ask if it would be possible if i could make a custom button or frame in
java. i got tired of using the build infeatures in java. i would like to create my own dessign of
button or frame.. can it be possible!!! /biggrin.gif' border='0' style='vertical-align:middle'
alt='biggrin.gif' /> thank!!!! /laugh.gif' border='0' style='vertical-align:middle'
alt='laugh.gif' /> New Help In! is NOT a descriptive topic title. Next time you decide not to
follow the posting rules, you will be issued a week long ban. ....
File Upload Script In Java
File Upload Script in JAVA (5) Hi, I am developing my personal website in JSP. I need a file upload script written in JAVA. I got a
script that is Upload Bean from javazoom.com but the problem is its working fine on Windows
Operating SYstem but not working on LINUX server. When i pass LINUX path (like
/home/usr/public_html) to bean it gives me error Check UploadBean properties in your JSP. I
think this bean aspecting a windows path. Can anyone provide me JSP Smart Upload script or any
other file upload bean in JAVA. For your information Smart Upload website has been closed. My
email id is ....
Java Mobile Applications
What you wanna have on your phone ? (9) I'm trying to do a Java mobile J2me application... But I don't know what to do... Any
suggestions....? Maybe you guys can say what you would like to have on your mobile phone... ....
[help] Java Script: Window.open
Works with Firefox, not IE (10) CODE var popUpWin=0; function popUpWindow(URLStr) { if(popUpWin) {
if(!popUpWin.closed) popUpWin.close(); } popUpWin = open(URLStr, 'GunBound Tactics:
Screenshots',
'width=820,height=550,menubar=no,resizable=yes,scrollbars=yes,toolbar=no,top=90,left=90'); }
Clips This is a script for opening a new window. It works with Firefox and not
Internet Explorer. IE gives a script error and it references a part of the code that has nothing to
do with the script. Someone please tell me if you can figure out why. Used at this add....
Learning Java
(11) Does anyone knows a good tutorial or book to learn Java?. I need to learn it quickly for a course in
the Uni. I have background in other programming languages such as C/C++ so i hope that helps. Thanks
in advance for your feedback....
Learning Java
By The Book (5) I travel alot so I get a chance to catch up on my reading. I bought a book today about javascripts.
I hope this will help me in creating my site which is currently being worked on. I want my site to
look professional and effective. I am hoping that this will help in creating this. Next I plan on
learning PHP, but since php is harder I will learn this first. I am a fast reader and I hope that I
can learn this fast since having a site down for a long time looks bad on the owner. One reason I
want to learn Javascript is to protect my site. I want to add a username and pa....
Java Is Not Javascript; Javascript Is Not Java
(2) Java, developed under the Sun Microsystems brand, is a full-fledged object-oriented programming
language. It can be used to create standalone applications and a special type of mini application,
called an applet. Applets are downloaded as separate files to your browser alongside an HTML
document, and provide an infinite variety of added functionality to the Web site you are visiting.
The displayed results of applets can appear to be embedded in an HTML page (e.g., the scrolling
banner message that is so common on Java-enhanced sites), but the Java code arrives as a separ....
Free online java compiler =)
no need to download the sun java SDK =) (6) Hey everyone, I found a site with a free online java compiler where you choose a source .java file
from your computer and click on compile on the webpage and you get instant .class files!
/biggrin.gif" style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" />.... heres the
link: www.innovation.ch - its somewhere on their website /smile.gif" style="vertical-align:middle"
emoid=":)" border="0" alt="smile.gif" /> Hope this helps in some way /wink.gif"
style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" />.......
Java Script Sites
(6) this is the best websites for javascript and other javascript.internet.com javascriptkit.com
webdeveloper.earthweb.com/webjs www.javascript.com www.dynamicdrive.com/
www.webdeveloper.com/javascript www.javascriptworld.com/scripts www.java-scripts.net
www.hotscripts.com www.totalscripts.com www.123webmaster.com www.needscripts.com www.reallybig.com
www.a1javascripts.com javascript.programmershelp.co.uk
developer.netscape.com/tech/javascript/resources.html
www.mountaindragon.com/javascript/resources.htm i'll make like this in cgi and php if u love
it???so....... ....
Java editor
(75) In your opinion what's the best java editor/compiler? i use jcreator le and it works nicely.......
Looking for implement, single, instance, application, java
|
Searching Video's for implement, single, instance, application, java
See Also,
|
advertisement
|
|