views:

88

answers:

4

Possible Duplicates:
How to implement a single instance Java application?
How do I make sure only one instance of my program can be executed?

What is a good and easy way to achieve this? I've read methods involving binding to a port. Will this interfere with other applications using the same method?

+1  A: 

Only if they use the same port, and there are a lot of ports. Just don't use one of the common ones.

Some software will also use some sort of lock file. Thus a second instance won't start if it exists.

Robin
A: 

The general concept is that you define a TCP port and then bind (listener/server) to it when your application starts. If you fail to bind to it, then you know another instance of your application is already running.

If another application is using the same port for something else (or for the same purpose), then this will fail. As such, it makes sense to put the port to use in a configuration file that exists outside your executable, so that the it can be configured to use one that's not already in use on the machine in question.

RHSeeger
A: 

You can indeed bind a ServerSocket to a specific TCP/IP port. If that port is already in use, bind will throw an IOException.

This method will not interfere with other applications that use the same method, unless another application happens to open the same port (TCP/IP ports are identified by a 16-bit number). So you should choose a fixed port number and hope that there are no other applications that by chance use the same port number.

Note that on Windows you can use the command netstat to see which ports are in use by which executables.

Jesper
+2  A: 

Not good to bind to a port. Try starting the application and resetting the network adapter, see what happens. Other applications could also need to use that port.

I think it's better to implement a lock on an external resource, such as a file, but care must be taken: if the pc reboots or something like that, it will be necessary to detect the stale locks.

Have you checked the Apache commons or JBoss projects yet? i bet there must be a library to do this correctly.

Mastermnd