Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Robert Tomsick Newsgroups: comp.lang.java.programmer Subject: Re: single instance Followup-To: comp.lang.java.programmer Date: Thu, 03 Jan 2013 01:20:29 -0500 Organization: A noiseless patient Spider Lines: 45 Message-ID: References: <50e357e9$0$291$14726298@news.sunsite.dk> Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit Injection-Date: Thu, 3 Jan 2013 06:20:32 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="d288f98bd942a963bd4b3f6fc3e5946f"; logging-data="7284"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19Kd0F5kU/b3lJNYXY8UFrtd+uqyW1aeZA=" X-Android-Status: Paranoid Cancel-Lock: sha1:HLTVIFgs11xXVjR1NW0phAi5qY0= Xref: csiph.com comp.lang.java.programmer:20914 Arne Vajhøj wrote: > On 1/1/2013 3:23 PM, Roedy Green wrote: >> What is the best way to ensure only a single instance of a Java >> program is running. >> >> I have used indicator files, but they can get screwed up if the user >> kills the program without going through the standard shutdown. > > 1) Some platform specific native code invoked via JNI. > > 2) A file and if found the app prompts the user to abort or continue. > > 3) Using IP port. Ok, so first, if you're doing a JWS app, you might want to try this: http://pscode.org/jws/api.html#sis and do as specified. Now if that's not the case then I'd go for a combination of #2 and #3. You can't catch all the failure modes, but you can at least eliminate the "user loves kill -9" threat. On launch of the first instance, your program could pick a random (high) port and open a socket. It then writes the port number to a temporary file at a known location. So now, on launch, all you have to do is check for the existance of that file. If it's not there, you start as normal, see above. If it is, you read the port number from the file, and try to connect to that socket. If you succeed, you assume the program's already running and whine to the user. If you fail, you assume the program was killed prematurely, you nuke the temp file, and proceed as normal. Of course that doesn't cover the case where your program gets whacked and something else starts listening on it in the meantime. You can work around that by having your program identify itself via said socket. It also doesn't handle the case where somebody deletes the temporary file while the app is running. Still, I suppose it's at least something of a decent platform-specific way of ensuring you're not allowing multiple instances of your program. All that said, I'd just use the typical pid file approach and assume that if the user decides to nuke the process they get to clean up the mess. -Rob