javasingletonmutual-exclusion

Get instance of same Java application if it is already running


Is it possible to check if a Java application is already running and if it is, get an instance of it? Say i have a jar that the first time it's clicked it opens a frame, and every time after that (until it's closed), it gets that frame and adds an object to it. This also needs to work without the main application having a close() method so the application will work again when reopened if it stops responding or it has been closed with task manager.


Solution

  • Java applications works on different process.

    So is not so easy to interact between two different process (already running application and the new one).

    What you can do is find a inter process communication mechanism and use it. Typical inter process communications use files or a common database.

    You can store the id of the current main thread executing your java app.

    If a new process starts check if there is an already running application. If yes, you can use the same (or a new one) inter process communication system to send information that the main process should update. Then the secondary process kill itself.