How do I make sure only one instance of my program can be executed?

后端 未结 6 562
旧时难觅i
旧时难觅i 2021-01-07 01:17

I want my program, a Java executable .jar, to be run just once. I made a program but now I want users not to be able to open more than one instance ....thanks for your time.

相关标签:
6条回答
  • 2021-01-07 01:48

    You could programmatically extract the jar file, http://www.devx.com/tips/Tip/22124, the update one file that will prevent the application from running anymore, then rejar it.

    The other option would be to just delete some critical class from the jar file, but neither of these will prevent it from being run again, as they can copy the jar file.

    You can't update a registry as there isn't a platform independent way to do that.

    0 讨论(0)
  • 2021-01-07 01:53

    You could use sockets - a ServerSocket can only listen on a port that's not already in use. The first launch successfully creates a ServerSocket instance on the port - while that program is running, no other ServerSocket can successfully be created on that port.

    import java.io.IOException;
    import java.net.ServerSocket;
    
    public class OneInstance {
    
        private static ServerSocket SERVER_SOCKET;
    
        public static void main(String[] args) {
            try {
                SERVER_SOCKET = new ServerSocket(1334);
                System.out.println("OK to continue running.");
                System.out.println("Press any key to exit.");
                System.in.read();
            } catch (IOException x) {
                System.out.println("Another instance already running... exit.");
            }
        }
    } 
    
    0 讨论(0)
  • 2021-01-07 01:58

    You can use a lock file solution. On startup of the application, have it check for a specific file. If it doesn't exist, create it and start the application normally. If it does exist, exit the application. You need to ensure the file is deleted when the application shuts down (maybe using a FileLock).

    0 讨论(0)
  • 2021-01-07 02:06

    it also depends what "more than one instance" means.

    1. once per machine -> tcp / mailslot / atom / fixed path
    2. once per user -> lock file in user homedir
    3. once user session -> a little more complicated and more dependent on platform
    0 讨论(0)
  • 2021-01-07 02:06

    There is an option in Launch4j http://sourceforge.net/projects/launch4j/ to restrict single instance of your java application.This potion is available in the fourth tab while creating wrapper for your java application.

    0 讨论(0)
  • 2021-01-07 02:14

    Java Web Start can handle this in a platform independent way, but you will need to let your program be started by Java Web Start which requires some tinkering.

    See http://download.java.net/jdk7/docs/technotes/guides/javaws/developersguide/examples.html#SingleInstanceService for how to let a single instance handle multiple "start me" requests.

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