This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

running only one instance of java program

 
arun shivanna
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about using singleton pattern.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simplest thing to do is to have your program try to open a socket - if it suceeds, its the only copy running. See java.net.ServerSocket.
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.
Bill
 
Tony Yan
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic