aspose file tools*
The moose likes Threads and Synchronization and the fly likes is static cache thead safe if it created in private constructor? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply locked New topic
Author

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

Margarita Babkova
Ranch Hand

Joined: May 09, 2012
Posts: 32
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

Joined: Oct 01, 2001
Posts: 2854
    
  11

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

Joined: May 09, 2012
Posts: 32
i have to add a second getInstance method without parameter - or come up with different idea.

Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2854
    
  11

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
Bartender

Joined: Jul 19, 2004
Posts: 5406
    
  13

Cross-post of this topic, discussion will continue here.

This thread is locked.


SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
http://www.javaroe.be/
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: is static cache thead safe if it created in private constructor?