How to implement a single instance Java application?

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

    I use the following method in the main method. This is the simplest, most robust, and least intrusive method I have seen so I thought that I'd share it.

    private static boolean lockInstance(final String lockFile) {
        try {
            final File file = new File(lockFile);
            final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            final FileLock fileLock = randomAccessFile.getChannel().tryLock();
            if (fileLock != null) {
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    public void run() {
                        try {
                            fileLock.release();
                            randomAccessFile.close();
                            file.delete();
                        } catch (Exception e) {
                            log.error("Unable to remove lock file: " + lockFile, e);
                        }
                    }
                });
                return true;
            }
        } catch (Exception e) {
            log.error("Unable to create and/or lock file: " + lockFile, e);
        }
        return false;
    }
    

提交回复
热议问题