i began actual work on my data class, and after some reading on this forum decided to use a singleton with lazy initialization; eager would be better but i am not sure how I will pass a database location.
I read it is possible by extending interface and provide database location through there...I am not sure i can use static block with hard coded value or have setter for dbPath, because i will still need class instance to use setter...
I am making a call to load a cache in a private constructor with argument, while I saw that some people where doing inside getInstance(String dbPath) method.
Will be my static variable cache thread save if it created this way?
I guess i will have to add second getInstance method without argument - but i really do not like it - becomes confusing, and needs good explanation. plus, more validation for dbPath if one already used.
both getInstance are synchronized.
Yes, that's generally right. Your constructor is commented out, but that's probably a typo. It wouldn't compile that way. It's unusual to have a parameter to a singleton's getInstance() method. Any call after the first will just return the already created instance, in effect ignoring the parameter entirely. That implies that you don't expect dbPath to change for the life of the application, and if that's true, why does the caller have to pass it in on each call?
posted 8 years ago
i have to add a second getInstance method without parameter - or come up with different idea.
If dbPath can change during the life of your application, then a singleton isn't the right way to go. In that case, a factory might work for you. If it can't change, then how does your caller figure out what value to use? It seems you could just move that logic inside your singleton and then the getInstance() method wouldn't need the parameter.