Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

only one program can run at the moment

 
Tiamo Toe
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Peter Kristensson
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic