1

I created application in Swing and i want to run only one instance of it. I wrote something like this:

private static final int PORT = 12345;
{
    try {
        new ServerSocket(PORT, 10, InetAddress.getLocalHost());
    } catch (UnknownHostException e) {
        // shouldn't happen for localhost
    } catch (IOException e) {
        // port taken, so app is already running
        System.out.println("Application already exist");
        System.exit(0);
    }
}

It works but only for all system. So if one user run it, another can't use it in the same time. So I want that each user could run only one instance of this application. Do you know how can i make it?

Koin Arab
  • 1,045
  • 3
  • 19
  • 35
  • Use Singleton Pattern. [http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java][1]. [1]: http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java – Sanira Mar 17 '15 at 16:02

1 Answers1

3

For each user, store the port number as a preference. The preference would be associated with the user account. The first time a user runs the application, the preference would not exist -- randomly generate a port number and store it for that user. Every time after that, when a user starts the application, read their port preference.

Since each user would use a different port, each user instance would not interfere with each other -- but each user would be limited to one instance.

martinez314
  • 12,162
  • 5
  • 36
  • 63
  • But what if the app will be suddenly interrupted? The preference will be still remembered and the app will not start. – Koin Arab Mar 18 '15 at 08:46