How to implement a single instance Java application?

后端 未结 17 744
北荒
北荒 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.

提交回复
热议问题