Koin Arab
Koin Arab

Reputation: 1107

Single instance of application per user in Java

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?

Upvotes: 1

Views: 137

Answers (1)

martinez314
martinez314

Reputation: 12332

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.

Upvotes: 3

Related Questions