简体   繁体   中英

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

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...

I've checked the server/client solution and the lock file, but I don't understand them much, I also tried to make them run in NetBeans, with no luck...

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.");
        }
    }
} 

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).

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.

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.

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

Launch4j http://sourceforge.net/projects/launch4j/中有一个选项来限制你的java应用程序的单个实例。这个药水在第四个选项卡中可用,同时为你的java应用程序创建包装器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM