I have created a Singleton for my class which contains an instance of MemcachedClient (this could be any object that requires making a connection to a server but I am providing a concrete example). I initialize the MemcachedClient in a static init block. If the MemcachedClient cannot create an instance due to a connection error, this now means my class is worthless because it has a null MemcachedClient instance.
My question: What is the best solution for this type of situation? How are other people handling this situation?
The question (as stated in the title) is too broad, it depends of what the singleton is for.
In your case, the obvious question: if the initialization fails, can you expect that the issue will be solved in the near future? What is the cost of keep trying (redesign so your app does not crashes downward in weird ways) instead of just rebooting your app?
If you do not expect the error to be solved easily, just crash your application (with the proper logs/alerts/notifications). If you want it to keep running until the issue resolves, then the steps would be:
1) Pass the initialization to the constructor of the singleton (why put it in a static block if you can control access to the constructor).
2a) While the constructor fails, calls to getInstance
will return null. Modify your application to be able to handle it.
2b) If the issue is present, create a singleton without the proper initialization. Calls to the methods of this objects will do nothing until the initialization issue has been solved / the object has been initialized. Modify your application to be able to handle these dummy methods. This method is swifter but way more complicated.
3) When a new instance is requested (if 2a) or a method is called (if 2b), check again if the object can be initialized.
Compare the cost of all the previous with the cost of just restarting your app after the issue has been solved.