How to implement a single instance Java application?

后端 未结 17 769
北荒
北荒 2020-11-22 04:32

Sometime I see many application such as msn, windows media player etc that are single instance applications (when user executes while application is running a new applicatio

相关标签:
17条回答
  • 2020-11-22 04:55

    You can use JUnique library. It provides support for running single-instance java application and is open-source.

    http://www.sauronsoftware.it/projects/junique/

    The JUnique library can be used to prevent a user to run at the same time more instances of the same Java application.

    JUnique implements locks and communication channels shared between all the JVM instances launched by the same user.

    public static void main(String[] args) {
        String appId = "myapplicationid";
        boolean alreadyRunning;
        try {
            JUnique.acquireLock(appId, new MessageHandler() {
                public String handle(String message) {
                    // A brand new argument received! Handle it!
                    return null;
                }
            });
            alreadyRunning = false;
        } catch (AlreadyLockedException e) {
            alreadyRunning = true;
        }
        if (!alreadyRunning) {
            // Start sequence here
        } else {
            for (int i = 0; i < args.length; i++) {
                JUnique.sendMessage(appId, args[0]));
            }
        }
    }
    

    Under the hood, it creates file locks in %USER_DATA%/.junique folder and creates a server socket at random port for each unique appId that allows sending/receiving messages between java applications.

    0 讨论(0)
  • 2020-11-22 04:56

    On Windows, you can use launch4j.

    0 讨论(0)
  • 2020-11-22 04:57

    I have found a solution, a bit cartoonish explanation, but still works in most cases. It uses the plain old lock file creating stuff, but in a quite different view:

    http://javalandscape.blogspot.com/2008/07/single-instance-from-your-application.html

    I think it will be a help to those with a strict firewall setting.

    0 讨论(0)
  • 2020-11-22 04:57

    You can open a Memory Mapped File and then see if that file is OPEN already. if it is already open, you can return from main.

    Other ways is to use lock files(standard unix practice). One more way is to put something into the clipboard when main starts after checking if something is already in the clipboard.

    Else, you can open a socket in a listen mode(ServerSocket). First try to connect to hte socket ; if you cannot connect, then open a serversocket. if you connect, then you know that another instance is already running.

    So, pretty much any system resource can be used for knowing that an app is running.

    BR, ~A

    0 讨论(0)
  • 2020-11-22 05:01

    You could try using the Preferences API. It is platform independent.

    0 讨论(0)
提交回复
热议问题