How to implement a single instance Java application?

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

    Yes this is a really decent answer for eclipse RCP eclipse single instance application below is my code

    in application.java

    if(!isFileshipAlreadyRunning()){
            MessageDialog.openError(display.getActiveShell(), "Fileship already running", "Another instance of this application is already running.  Exiting.");
            return IApplication.EXIT_OK;
        } 
    
    
    private static boolean isFileshipAlreadyRunning() {
        // socket concept is shown at http://www.rbgrn.net/content/43-java-single-application-instance
        // but this one is really great
        try {
            final File file = new File("FileshipReserved.txt");
            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;
    }
    

提交回复
热议问题