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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

But what if the app will be suddenly interrupted? The preference will be still remembered and the app will not start.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.