Howdy Ranchers!
I am working on Data class as a singleton
pattern. Firstly I created a thread-safe singleton by initializing the instance as a class field like this (not relevant parts were cut):
But when the Data class is creating, it reads underlying database file. I would like not to catch exceptions thrown when reading the file, but rather bubble them up to the business logic layer and then send to client to inform that sever error occured. I cannot throw exceptions from the constructor, because I create an object of the class as a field. The only thing I could came up with is to move the read code into getInstance() method which can throw exceptions like this:
My concern is thread-safety of this solution. There is only one instance of the object (it is created when loading class) so it's fine, but two threads can access the same object's method (getInstance()) and do something like:
T1: instance.recordCache == null -> TRUE
T2: instance.recordCache == null -> TRUE
T1: instance.recordCache = instance.dataAccessor.read();
T2: instance.recordCache = instance.dataAccessor.read();
And I've ended with loading the records twice. It is not a big problem, as it won't corrupt any data, but it is an overhead which I don't need.
I can synchronize whole getInstance() method, but won't this impact a performance a lot?
What do you think about it?
How would you solve a problem of throwing an exceptions from singleton?
Do you see any design flaws in my approach?
Do you find it more coherent to create whole object in getInstance() method instead of instantiasing it as a field AND then doing some reading operations in getInstance() method?
Thanks in advance Guys!
-----
EDIT: One of the possibilities is to throw a Runtime Exception from the static initializer block, but it will made me to wrap my checked exception into runtime exception and then (in business logic layer) back to checked one for the GUI... This smells, don't you think?