Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is static initialization of a class varaible guaranteed to occur only once?

 
SAFROLE YUTANI
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In other words, if two threads attempt to create an instance of this class, would the static initialization of ConnectionFactory occur once?
public ConnectionSource {
private static ConnectionFactory factory = new ConnectionFactory();
}
I need exactly one instance of ConnectionFactory.
SAF
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope, that will not do what you want.
What you need is a way to check for a second attempt to initialize the reference and prohibit it. This is described by a design pattern known as a Singleton. It works something like this:

This way your object can only be constructed within the class, and the code that executes is subject to a verification.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To answer the original question - yes, static initialization is guaranteed to occur only once for a given class. However your program does not guarantee that no other code will be able to instantiate a second instance, and that is the problem which Michael's code addresses.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If ConnectionFactory is a class over whose instantiation you have complete control, then using the Singleton pattern may be unnecessary. Appropriate documentation may be sufficient and is cheaper (in terms of byte code and execution time).
This would certainly be the case if ConnectionFactory were a private inner class of ConnectionSource. You might argue that it was still the case if ConnectionFactory were package-private in the same package as ConnectionSource; this depends on how your code is distributed and maintained.
If you want ConnectionFactory to be a public class and to allow code outside its package to instantiate it, but you want to prevent more than one instance being created, then Singleton is definitely the way to go.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic