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

前端 未结 11 1733
你的背包
你的背包 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:51

    Following solution work in two deadly scenerio too. 1> Even your launched exe scheduled as javaw.exe in task manager. 2> You can install your application at two location and from launching both location it also works.

    String tempDir = System.getProperty("java.io.tmpdir");// dependent to OS find any tem dir.
            String filePath = tempDir + "lockReserverd.txt";
            try {
                final File file = new File(filePath);
    
                if(file.exists())
                    return false;
    
                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");
            }
            return false
    

    or

    This will work if your application.exe is listed in task manager

    "tasklist /FI \"IMAGENAME eq "+MyApplication+".exe
    

提交回复
热议问题