How to make sure that only a single instance of a Java application is running?

前端 未结 11 1737
你的背包
你的背包 2020-12-09 20:23

I want my application to check if another version of itself is already running.

For example, demo.jar started, user clicks to run it again, but the sec

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 20:43

    Here is one method that uses an automatically named lock file in the user's home directory. The name is based on where the jar is being ran from.

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.channels.FileChannel;
    
    public class SingleInstance {
    
        @SuppressWarnings("resource")
        public static boolean isAlreadyRunning() {
            File file;
            FileChannel fileChannel;
            File userDir = new File(System.getProperty("user.home"));
            file = new File(userDir, myLockName());
    
            if (!file.exists()) {
                try {
                    file.createNewFile();
                    file.deleteOnExit();
                } catch (IOException e) {
                    throw new RuntimeException("Unable to create Single Instance lock file!", e);
                }
            }
    
            try {
                fileChannel = new RandomAccessFile(file, "rw").getChannel();
            } catch (FileNotFoundException e) {
                throw new RuntimeException("Single Instance lock file vanished!", e);
            }
            try {
                if (fileChannel.tryLock() != null) {
                    return false;
                }
            } catch (Exception e) {
            }
            try {
                fileChannel.close();
            } catch (IOException e1) {
            }
            return true;
        }
    
        private static String myLockName() {
            return "." + SingleInstance.class.getProtectionDomain().getCodeSource().getLocation().getPath()
                    .replaceAll("[^a-zA-Z0-9_]", "_");
        }
    }
    

提交回复
热议问题