Bookmark Topic Watch Topic
  • New Topic

is static cache thead safe if it created in private constructor?

 
Margarita Babkova
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Report post to moderator
hi there,

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...
For now
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.



thank you in advance.
 
Greg Charles
Sheriff
Posts: 2989
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Report post to moderator
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?
 
Margarita Babkova
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Report post to moderator
i have to add a second getInstance method without parameter - or come up with different idea.

 
Greg Charles
Sheriff
Posts: 2989
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Report post to moderator
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.
 
Roel De Nijs
Sheriff
Posts: 10404
133
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Report post to moderator
Cross-post of this topic, discussion will continue here.

This thread is locked.
 
    Bookmark Topic Watch Topic
  • New Topic