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

I want my Java.jar program to run only once. I made a program, but now I want users to not be able to open multiple instances ... thanks for your time ...

I checked the server / client solution and the lock file, but I do not really understand them, I also tried to get them to work in NetBeans, no luck ...

+2
source share
6 answers

You can use sockets - ServerSocket can only listen on a port that is not yet in use. The first start successfully creates an instance of ServerSocket on the port - while this program is running, no other ServerSocket server can be successfully created on this 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.");
        }
    }
} 
+7
source

You can use the solution to block files. When starting the application, check it for a specific file. If it does not exist, create it and run the application as usual. If it exists, exit the application. You need to make sure that the file is deleted when the application shuts down (possibly using FileLock).

+7
source

jar, http://www.devx.com/tips/Tip/22124, , , rejar .

, - jar, , jar.

, .

0

it also depends on what “more than one instance” means.

  • once per machine -> tcp / mailslot / atom / fixed path
  • once for the user -> lock file in user homedir
  • after a user session -> a little more complex and more platform dependent
0
source

In Launch4j http://sourceforge.net/projects/launch4j/ to limit one instance of your java application. This potion is available on the fourth tab when creating a wrapper for your Java application.

0
source

Source: https://habr.com/ru/post/1761787/


All Articles