How to implement a single instance Java application?

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

    We use file locking for this (grab an exclusive lock on a magic file in the user's app data directory), but we are primarily interested in preventing multiple instances from ever running.

    If you are trying to have the second instance pass command line args, etc... to the first instance, then using a socket connection on localhost will be killing two birds with one stone. General algorithm:

    • On launch, try to open listener on port XXXX on localhost
    • if fail, open a writer to that port on localhost and send the command line args, then shutdown
    • otherwise, listen on port XXXXX on localhost. When receive command line args, process them as if the app was launched with that command line.

提交回复
热议问题