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
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
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
Joined: Mar 03, 2003
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 ?
Joined: Jan 30, 2002
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