It's not a secret anymore!
The moose likes Servlets and the fly likes running only one instance of java program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "running only one instance of java program" Watch "running only one instance of java program" New topic

running only one instance of java program

arun shivanna

Joined: Jul 09, 2003
Posts: 2
I would like run only one instance of my program.
if one instance is running, i should get a message it is already running.
now if i can run 'n' number of instances.
like "i have QsFrame class which is main class"
if i run "java QsFrame" then until i exit from this frame i should run another instance.
Javed Sardar
Ranch Hand

Joined: Sep 10, 2002
Posts: 33
How about using singleton pattern.
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
won't work.
Singleton prevents multiple instances inside a single JVM but nothing will prevent the starting of multiple JVMs on the same machine.
You will need some means of cross-JVM communication to check whether a specific class (say your application's main class) is loaded inside the other JVMs and if it is stop the application from loading.
Whether such a system exists or is even possible I can't tell, never having tried it.
An alternative might be to set up a shared resource that keeps track of the application being loaded (maybe a simple file or database field).
Major disadvantage of that approach is that if the application is improperly terminated (crashes, gets killed, etc) the resource will still show the application as running and now no instances can be started at all.

William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
The simplest thing to do is to have your program try to open a socket - if it suceeds, its the only copy running. See
This is not really a servlet question - if I find you have asked this question in a bunch of other forums I shall be very annoyed.
Tony Yan
Ranch Hand

Joined: Apr 10, 2002
Posts: 170
A good solution. To extend that, if it is on a single OS, any IO source locking can be used for controlling that, besides socket.

Tony Yan<br /> <br />IBM Certified Developer XML and Related Technology<br />Sun Certified Web Component Developer For J2EE Platform<br />Sun Certified Programmer For Java 2 Platform
I agree. Here's the link:
subject: running only one instance of java program
It's not a secret anymore!