• Post Reply Bookmark Topic Watch Topic
  • New Topic

singletoning an application  RSS feed

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to assure that the singleton class hasn't more than one instance.
Meanwhile the "singleton" only assures the uniqueness of the object per application.
What are my options to assure that the application does not have more than one instance running (instantiated concurrently) and therefore a "singleton" instantiated in various applications?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The easiest way is to use either a socket or a file as a "semaphore". If the entity you want to "singletonize" opens a ServerSocket on some well-known port (pick something like port 12345, not normally used) then only the first one to attempt it to succeed; later ones will try and fail. Of course, with this technique there's a small but real chance that some other application will use this port as a transient port. Instead, then, you can use a file -- i.e.,
MyProgramData/.lock. The program should check for that file on startup, and exit if it's already there; otherwise, it should create the file. You can use File.setDeleteOnExit() to clean it up automatically if you want, or do it in a shutdown handler.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Ernest,
I was thinking about Properties or ResourceBundle. But I have heard that writing to file is atomic.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THough, it is not quite good. If PC is rebooted or hang up, the file remains there and application will not be able to initiate itself
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!