This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes only one program can run at the moment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "only one program can run at the moment" Watch "only one program can run at the moment" New topic
Author

only one program can run at the moment

Tiamo Toe
Greenhorn

Joined: Mar 03, 2003
Posts: 2
i have a program MyApp
Each time i type at command line:
java MyApp
the program will run in a new window. But i want only one instance of program will remain.
I want my program to check if any instance of it is exist then it will terminate. How can i do that ?
Thanks in advance and sorry for my poor English
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Greetings, Mr. Train is it? Welcome to JavaRanch the absolute best site in the whole www for Java information. We don't have many rules around here but we do have one. Your display name should be a real first and last name according to JavaRanch Naming Policy. You can edit your profile here MyProfile.
Michael Morris
[ March 03, 2003: Message edited by: Michael Morris ]

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Peter Kristensson
Ranch Hand

Joined: Jul 02, 2001
Posts: 118
Hiya.
You can use a lock-file for this.
Each time you start your program, you check if the lock-file is present, and if it is, you shut down the program.
If the file isn't in place, simply create it and start the rest of the program.
Oh, and don't forget to remove the lock-file then you exit your program.
/Peter
Tiamo Toe
Greenhorn

Joined: Mar 03, 2003
Posts: 2
i dont think lock file is a good solution. What will happen if your program crash ? Your lock file will not be deleted.
Any other solution ?
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Tiamo,
A quick and dirty solution would be to open a ServerSocket on some free (hard encoded) port. Then any new instance would throw a BindException upon trying to open the same port. You can just catch the BindException and print a message in the catch block that only one instance may run and gracfully exit. Even if the program crashes, then the port should eventually be freed by the system.
Hope this helps,
Michael Morris
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: only one program can run at the moment
 
Similar Threads
how to remove the port number in URL
Integrating jforum with existing app
Mapping JSP
Environment variables (Win 2K)
new command window