There is a task to prevent the application from being re-executed while it is being executed. Ie, to prevent the launch of the second instance. In C, I used mutexes to solve this issue, but what can and should I use in Java?

  • If you are given an exhaustive answer, mark it as correct (tick the selected answer). - andreycha

1 answer 1

Depends on what the application does.
If this is any server, it is logical to create a ServerSocket with a fixed address and port.
You can exclusively block a specific file:

 FileChannel.open(Paths.get(".../file.lock"), StandardOpenOption.WRITE, StandardOpenOption.CREATE).tryLock() 

(file must be writeable).
The option to simply create a file exclusively ( StandardOpenOption.CREATE_NEW ) is not reliable, since there is no guarantee that you will be able to delete the file on exit, so that the next time you start the application will consider that it is already running.

  • I had the same thoughts for a file or a socket. But he considered a collective farm. Ie, what elegant solutions do you have? - Kamenev_D
  • @Kamenev_D Collective farm / elegance is a subjective matter. There are no OS-level Mutexes in java, because it may be difficult to implement them cross-platform. If you read similar questions in English SO ( one , two ), then they offer the same thing as me, well, still native-calls. - Roman
  • Clear. If you work through a file, the application opens it in exclusive mode, and if you cannot open it, then the application is running. Do you understand correctly? - Kamenev_D
  • @Kamenev_D No, the application opens the file for writing in normal mode, and only then tries to get FileLock . If failed to get, another application is already running. Theoretically, the presence of FileLock can even prevent the opening of a file in another application, this should be checked. - Roman