How to implement a single instance Java application?

后端 未结 17 1009
北荒
北荒 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:42

    The Unique4j library can be used for running a single instance of a Java application and pass messages. You can see it at https://github.com/prat-man/unique4j. It supports Java 1.6+.

    It uses a combination of file locks and dynamic port locks to detect and communicate between instances with the primary goal of allowing only one instance to run.

    Following is a simple example of the same:

    import tk.pratanumandal.unique4j.Unique4j;
    import tk.pratanumandal.unique4j.exception.Unique4jException;
    
    public class Unique4jDemo {
    
        // unique application ID
        public static String APP_ID = "tk.pratanumandal.unique4j-mlsdvo-20191511-#j.6";
    
        public static void main(String[] args) throws Unique4jException, InterruptedException {
    
            // create unique instance
            Unique4j unique = new Unique4j(APP_ID) {
                @Override
                public void receiveMessage(String message) {
                    // display received message from subsequent instance
                    System.out.println(message);
                }
    
                @Override
                public String sendMessage() {
                    // send message to first instance
                    return "Hello World!";
                }
            };
    
            // try to obtain lock
            boolean lockFlag = unique.acquireLock();
    
            // sleep the main thread for 30 seconds to simulate long running tasks
            Thread.sleep(30000);
    
            // try to free the lock before exiting program
            boolean lockFreeFlag = unique.freeLock();
    
        }
    
    }
    

    Disclaimer: I created and maintain Unique4j library.

提交回复
热议问题