Why declare self static instance of a class - java

I sometimes see that people create self instance for example:
public class Example extends Service
{
private static Example mInstance = null;
public void onStart( Intent aIntent, int aStartId )
{
mInstance = this;
.
.
.
}
}
What is the purpose of this?

This is called the Singleton design pattern. Singletons are used when there is going to be a single instance of an object performing operations on non-static data.
See here.

In addition to what other answers put about Singleton pattern, self instances may be used as constants. That's the case of the Color class, that defines an instance for each of the common colours.
http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html

An Android Service (sub)class cannot be a singleton since the framework requires access to a default constructor for the class. The only reason I can think of for keeping a static reference to the (last) instance for which onStart was called is to simplify some internal code that may happen to reside in static methods.
Considering that onStart was deprecated a long time ago (as of API level 5), this is most likely an example of bad coding style from early days of Android.

So that other classes can get an instance and call instance methods on the object. Its frequently used with the Singleton pattern. And for Services and Activities in Android it's a very bad idea- it keeps a reference to the Activity/Service around after it ends, which will cause a memory leak.

In a thread-unsafe singleton pattern implementation, you would have a private constructor, and a public static getInstance method initializing that instance if necessary and returning it.
Here's an example. Note that it is advised to leverage the commodity of a single-element enum instead of the code below, to achieve a "true" singleton.
public class MyThreadUnsafeSingleton {
private static MyThreadUnsafeSingleton instance;
private MyThreadUnsafeSingleton() {
//TODO some ctor logic
}
public static MyThreadUnsafeSingleton getInstance() {
if (instance == null) {
instance = new MyThreadUnsafeSingleton();
}
return instance;
}
}
Final note, there is a variation of the above pattern that is thread-safe across a single classloader through the usage of a nested "holder" class, but that's quite out of scope.

If it has a private default constructor, it's probably a singleton.
If it doesn't, it's something weird.
This sort of layout forces all object instances of this class to share data, regardless of when they are instantiated. The object instance on which OnStart is called will become the underlying data source for any references to this class, regardless of when they were declared or instantiated (before or after OnStart), and regardless of what thread they were created on.
Of course it is always possible there are members of the class that don't bother with mInstance.Member and use this.Member instead. That sort of mixing and matching would probably end up being disastrous.
It's hard to imagine the specific use for this but my guess is that the class is an abstraction of some stateful resource that is global with respect to the process, e.g. a form/window or a web service client that caches its credentials. Could be anything though.
If this code was written around 2003-2005 (early c# days) I'd guess that it is a sloppy implementation of a Singleton-- it was sort of in vogue back then as design patterns were becoming a thing and Singleton was the example in all the textbooks. Turns out it's a horrible pattern for dependency injection and mocking, so these days this pattern doesn't get used as much.

This paradigm is often used for objects that are heavy or slow to construct and only one is needed.
public class Server {
private static Server server = null;
// Stop them making their own.
private Server () {
// Heavyweight stuff.
}
public static Server getServer () {
if ( server == null ) {
// Heavy constructor.
server = new Server();
}
return server;
}
}
In a multi-thread environment it is usually combined with the singleton design pattern.

Related

Benefit of interface for getInstance call? [duplicate]

Is the Initialize-On-Demand idiom really necessary when implementing a thread safe singleton using static initialization, or would a simple static declaration of the instance suffice?
Simple declaration of instance as static field:
class Singleton
{
private static Singleton instance=new Singleton();
private Singleton () {..}
public static Singleton getInstance()
{
return instance;
}
}
vs
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
private Singleton () {..}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
I ask this because Brian Goetz recommends the 1st approach in this article:
http://www.ibm.com/developerworks/java/library/j-dcl/index.html
while he suggests the latter in this article
http://www.ibm.com/developerworks/library/j-jtp03304/
Does the latter approach provide any benefits that the former doesn't?
Well what i can say These articles are 7-9 years old.
Now we have > Java 1.5 where we have power of enumeration enum. According to 'Josh Block' The best way to write a singleton is to write a Single Element enum
public enum MySingleton{
Singleton;
// rest of the implementation.
// ....
}
But for your question I guess there is no issue in using either of the implementations. I personaly prefer the first option because its straightforward, simple to understand.
But watch out for the loop holes that we can be able to create more objects of these class in the same JVM at the same time by serializing and deserializing the object or by making the clone of the object.
Also make the class final, because we can violate the singleton by extending the class.
In first approach your singleton will get created once you load Singleton class. In the other, it will get created once you call getInstance() method. Singleton class may have many reasons to get loaded before you call getInstance. So you will most likely initialize it much earlier when you actually use it and that defeats the purpose of lazy initialization. Whether you need lazy initialization is a separate story.
The simple declaration pattern constructs the singleton when when the class Singleton is loaded. The initialize-on-demand idiom constructs the singleton when Singeton.getInstance() is called -- i.e., when class SingetonHolder is loaded.
So these are the same except for time; the second option allows you delay initialization. When to choose one or the other depends on (among other things) how much work you are doing in Singleton's constructor. If it's a lot, you may see improved application startup time with initialization-on-demand.
That said, my advice is to try not to do too much there so that the simplest pattern works for you.
-dg

Confusion between Singleton and Static method Java

Suppose I want to implement the class which will provide me Connection for database connectivity. I can implement the same thing with two different code snaps given below.
Method 1:
class DBConnection1 {
private static DBConnection1 instance = new DBConnection1();
private DBConnection1(){
}
public static DBConnection1 getInstance(){
return instance;
}
public Connection getConnection(){
Connection connection = null;
//do my stuff to init the connection
return connection;
}
}
Method 2:
class DBConnection2 {
public static Connection getConnection(){
Connection connection = null;
//do my stuff to init the connection
return connection;
}
}
And Accessing the above methods like,
class TestConnection{
public static void main(String[] args) {
//using method 1
Connection connection1 = DBConnection1.getInstance().getConnection();
//using method 1
Connection connection2 = DBConnection2.getConnection();
}
}
I have little doubt which is better and why? And what is difference over there?
At a very high level you might get confused and it looks that they both are doing the same task. But there is a lot of difference. I'm answering this question in general. You can understand the advantages based on your application(type).
Singleton stores common data in only one place. It will greatly simplify the architecture of a program and helps you to reuse code. Singletons allow you control object state much easier. This improves code-sharing, and quality of code. Hence it becomes easier to maintain. Singleton allows you to override in case you want to override it. Lazy loading can be done using Singleton Classes. Singleton is more object oriented. Static objects are stored in stack but singleton objects are stored in heap.
Static classes are difficult to test when compared to Singleton(Singleton is very easy to mock. Eg- while using JUnit Tests). If you are using Spring or any such dependency injection framework, its better to use Singleton than static. Static Class cannot be passed to a method or inherited. Static classes can create issues in a concurrent environment due to shared data. its better not to maintatin state inside static class. You can refer more about Singleton here http://en.wikipedia.org/wiki/Singleton_pattern or http://www.tutorialspoint.com/java/java_using_singleton.htm .
The only advantage that i see with static class is that its faster. Use static only when a set of functions have to be kept together.
Depends on what you try to achieve. For example, if you are sure that you'll need this connection through all your app lifecycle - static method is for you. But if you are not sure about that - use singleton. But in real projects you should probably not use static methods for anything but some kind of utils methods, because singleton is much more flexible comparing to a static methods.
But there are minimum one more pattern that you'll probably be interested in. Dependency injection. It could be a little bit more complex than a singleton, but again it's much more flexible. The main point of if that in a big project you may need some functionality providing by database and you'll use one class to access it. But later data separated by two databases and two classes with the same interface and instead if rewriting the code of classes that use a database, you changed implementation that would be injected in a particular class. There are much more benefits of using dependency injection that I described, but I hope you'll got the point.
The two alternatives are equivalent. However, I would prefer the singleton one, because it is easier to swap the implementation or override behavior with subclassing in the future.
Another point that will make much more difference is whether to create a new connection for every use or reuse connection objects. This will make a lot of difference concerning prepared statements and commits / rollbacks.
You are mixing up two different patterns, namely Static Factory Method (not the same as the GoF Factory Method) and Singleton.
Static Factory Method is concerned with creating instances. The Singleton pattern is used to ensure, that there is only one object of the Singleton class.
E.g. a typical static factory method:
public DBConnection {
private DBConnection(String param) {
//...
}
public static DBConnection createConnection(String param) {
return new DBConnection(param);
}
}
Note, that typically a factory method is called create... or getNewInstance or something similar to emphasize, that this method will always return a new instance.
The same as a Singleton:
public DBConnection {
private static DBConnection instance;
private DBConnection(String param) {
//...
}
public static DBConnection getInstance() {
if(instance == null){
instance = new DBConnection("fixed param!");
}
return instance;
}
}
Note how the same instance is always returned after it was created lazily.
Nevertheless those pattern can coexist - e.g. a singleton can use a static factory method to create the instance:
public DBConnection {
private static DBConnection instance;
private DBConnection(String param) {
//...
}
public static DBConnection createInstance(String param) {
return new DBConnection(param);
}
public static DBConnection getInstance() {
if(instance == null){
instance = DBConnection.createInstance("param");
}
return instance;
}
}
I intentionally left the static factory method public, to emphasize the difference between getInstance and createInstance here.
Also private constructors play an important role in those patterns it enforces that the createInstance / getInstance methods must be used to get hold of an instance.
The short answer is that you should not use the Singleton approach. This is because you seem to be returning a new connection everytime the getConnection method is called. If this is what you really want, there is no point using a Singleton class. You should go with method 2 instead.
The long answer is that you seem to be confused about what a Singleton really is. The purpose of a Singleton class is to ensure that there is only one object of a given class created for a given ClassLoader, thus ensuring that the state of such an object is global. If your class does not contain any state, you might as well use a class that contains only static methods. Alternately, if you are using an IoC container such as Spring or Guice, you can have a Singleton enforced via the framework rather than explicitly design your class as a Singleton. A class that is explicitly designed to be a Singleton but does not have any state really doesn't make much sense.
If you plan to have a connection factory, better to to implement method1.
Because you could change you code inside of you Factory with few impact in the rest of the App.
Caution if reusing the connection, since you can share context, and that can be something you don't want!
Better is to live the ConnectionFactory get from connection's pool, one connection, then using it, then releasing it.... etc.
See factory pattern : if this is a connection factory that serves connections, better to see Factory Method Pattern

Singleton Pattern

This question, like my previous question, references Effective Java. This time I have quite a few sub-questions.
A privileged client can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible() method. If you need to defend against this, modify the constructor.
How, exactly, can a private constructor be invoked? And what is AccessibleObject.setAccessible()?
What approach do you experts follow with singletons?
// Approach A
public class Test{
public static final Test TestInstance = new Test();
private Test(){ ... }
.
.
.
}
// Approach B
public class Test{
private static final Test TestInstance = new Test();
private Test(){ ... }
public static Test getInstance() { return TestInstance; }
.
.
.
}
Isn't the second approach more flexible, in case we have to make a check for new instances every time or the same instance every time?
What if I try to clone the class/object?
a single-element enum type is the best way to implement a singleton.
Why? How?
A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
Obviously a private constructor can be invoked by the class itself (e.g. from a static factory method). Reflectively, what Bloch is talking about is this:
import java.lang.reflect.Constructor;
public class PrivateInvoker {
public static void main(String[] args) throws Exception{
//compile error
// Private p = new Private();
//works fine
Constructor<?> con = Private.class.getDeclaredConstructors()[0];
con.setAccessible(true);
Private p = (Private) con.newInstance();
}
}
class Private {
private Private() {
System.out.println("Hello!");
}
}
2.What approach do you experts follow with singletons:
...
Typically, the first is favoured. The second (assuming you were to test if TestInstance is null before returning a new instance) gains lazy-loading at the cost of needing to be synchronized or being thread-unsafe.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, the above consideration is irrelevant.
Isn't the second approach more flexible in case we have to make a check for new instance every time or same instance every time?
It's not about flexibility, it's about when the cost of creating the one (and only) instance is incurred. If you do option a) it's incurred at class loading time. That's typically fine since the class is only loaded once it's needed anyway.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, in both cases the Singleton will be created at class load.
What if I try to clone the class/object?
A singleton should not allow cloning for obvious reasons. A CloneNotSupportedException should be thrown, and will be automatically unless you for some reason implement Cloneable.
a single-element enum type is the best way to implement a singleton. Why? and How?
Examples for this are in the book, as are justifications. What part didn't you understand?
Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most over-used patterns. It's gotten to the point that some consider them an "anti-pattern". The best advice is to "use them wisely."
For a great introduction to this, and many other useful patterns (personally, I find Strategy, Observer, and Command to be far more useful than Singleton), check out Head First Design Patterns.
A priviledged cleint can invoke the private constructor reflectively with
the aid of the
AccessibleObject.setAccessible method,
If you need to defend this, modify the
constructor. My question is: How
exactly can a private constructor is
invoked? and what is
AccessibleObject.setAccessible??
You can use java reflection to call private constructors.
What approach do you experts follow with singletons:
I am a fan of using enum to actually do this. This is in the book also. If that's not an option, it is much simpler to do option a because you don't have to check or worry about instance being already created.
What if I try to clone the
class/object?
Not sure what you mean? do you mean clone() or something else that I don't know of?
a single-element enum type is the best way to implement a singleton.
Why? and How?
Ahh my own answer. haha. This is the best way because in this case, the java programming language guarantees a singleton instead of the developer having to check for a singleton. It's almost as if the singleton was part of the framework/language.
Edit:
I didn't see that it was a getter before. Updating my answer to this - it's better to use a function such getInstance because you can control what happens through a getter but you can't do the same if everybody is using a reference directly instead. Think of the future. If you ended up doing SomeClass.INTANCE and then later you wanted to make it lazy so it doesn't load right away then you would need change this everywhere that its being used.
The first rule of the Singleton (Anti-) Pattern is don't use it. The second rule is don't use it for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, especially if it is a dependency of those classes. Use dependency injection instead. There are valid uses for Singletons, but people have a tendenecy to badly misuse them because they're so "easy" to use. They make it very difficult to test classes that depend on them and make systems inflexible.
As far as your questions, I think 1, 2 and 3 can all be answered by saying "use an enum-singleton". Then you don't need to worry about constructor accessiblity issues, clone()ing, etc. As far as 4, the above is a good argument for them. I also have to ask, did you read the section in Effective Java that explicitly answers your question?
Example singleton lazy init:
Class main:
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
Class singleton:
public class Singleton {
private static Singleton instance;
public String value;
private Singleton (String s){
this.value =s;
}
public static Singleton getInstance(String param) {
if (instance == null)
instance = new Singleton(param);
return instance;
}
}
When start application, console will contains next strings:
first
first
first
\|/ 73

What are static factory methods?

What's a "static factory" method?
The static factory method pattern is a way to encapsulate object creation. Without a factory method, you would simply call the class's constructor directly: Foo x = new Foo(). With this pattern, you would instead call the factory method: Foo x = Foo.create(). The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as static so that it can be called without first having an object.
There are a few advantages to this pattern. One is that the factory can choose from many subclasses (or implementers of an interface) and return that. This way the caller can specify the behavior desired via parameters, without having to know or understand a potentially complex class hierarchy.
Another advantage is, as Matthew and James have pointed out, controlling access to a limited resource such as connections. This a way to implement pools of reusable objects - instead of building, using, and tearing down an object, if the construction and destruction are expensive processes it might make more sense to build them once and recycle them. The factory method can return an existing, unused instantiated object if it has one, or construct one if the object count is below some lower threshold, or throw an exception or return null if it's above the upper threshold.
As per the article on Wikipedia, multiple factory methods also allow different interpretations of similar argument types. Normally the constructor has the same name as the class, which means that you can only have one constructor with a given signature. Factories are not so constrained, which means you can have two different methods that accept the same argument types:
Coordinate c = Coordinate.createFromCartesian(double x, double y)
and
Coordinate c = Coordinate.createFromPolar(double distance, double angle)
This can also be used to improve readability, as Rasmus notes.
NOTE! "The static factory method is NOT the same as the Factory Method pattern" (c) Effective Java, Joshua Bloch.
Factory Method: "Define an interface for creating an object, but let the classes which implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" (c) GoF.
"Static factory method is simply a static method that returns an instance of a class." (c) Effective Java, Joshua Bloch. Usually this method is inside a particular class.
The difference:
The key idea of static factory method is to gain control over object creation and delegate it from constructor to static method. The decision of object to be created is like in Abstract Factory made outside the method (in common case, but not always). While the key (!) idea of Factory Method is to delegate decision of what instance of class to create inside Factory Method. E.g. classic Singleton implementation is a special case of static factory method. Example of commonly used static factory methods:
valueOf
getInstance
newInstance
We avoid providing direct access to database connections because they're resource intensive. So we use a static factory method getDbConnection that creates a connection if we're below the limit. Otherwise, it tries to provide a "spare" connection, failing with an exception if there are none.
public class DbConnection{
private static final int MAX_CONNS = 100;
private static int totalConnections = 0;
private static Set<DbConnection> availableConnections = new HashSet<DbConnection>();
private DbConnection(){
// ...
totalConnections++;
}
public static DbConnection getDbConnection(){
if(totalConnections < MAX_CONNS){
return new DbConnection();
}else if(availableConnections.size() > 0){
DbConnection dbc = availableConnections.iterator().next();
availableConnections.remove(dbc);
return dbc;
}else {
throw new NoDbConnections();
}
}
public static void returnDbConnection(DbConnection dbc){
availableConnections.add(dbc);
//...
}
}
Readability can be improved by static factory methods:
Compare
public class Foo{
public Foo(boolean withBar){
//...
}
}
//...
// What exactly does this mean?
Foo foo = new Foo(true);
// You have to lookup the documentation to be sure.
// Even if you remember that the boolean has something to do with a Bar
// you might not remember whether it specified withBar or withoutBar.
to
public class Foo{
public static Foo createWithBar(){
//...
}
public static Foo createWithoutBar(){
//...
}
}
// ...
// This is much easier to read!
Foo foo = Foo.createWithBar();
have names, unlike constructors, which can clarify code.
do not need to create a new object upon each invocation - objects
can be cached and reused, if necessary.
can return a subtype of their return type - in particular, can
return an object whose implementation class is unknown to the caller.
This is a very valuable and widely used feature in many frameworks
which use interfaces as the return type of static factory methods.
fromhttp://www.javapractices.com/topic/TopicAction.do?Id=21
It all boils down to maintainability. The best way to put this is whenever you use the new keyword to create an object, you're coupling the code that you're writing to an implementation.
The factory pattern lets you separate how you create an object from what you do with the object. When you create all of your objects using constructors, you are essentially hard-wiring the code that uses the object to that implementation. The code that uses your object is "dependent on" that object. This may not seem like a big deal on the surface, but when the object changes (think of changing the signature of the constructor, or subclassing the object) you have to go back and rewire things everywhere.
Today factories have largely been brushed aside in favor of using Dependency Injection because they require a lot of boiler-plate code that turns out to be a little hard to maintain itself. Dependency Injection is basically equivalent to factories but allows you to specify how your objects get wired together declaratively (through configuration or annotations).
If the constructor of a class is private then you cannot create an object for class from outside of it.
class Test{
int x, y;
private Test(){
.......
.......
}
}
We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class?
Here is the Answer : FACTORY method.
Add the below method in above class
public static Test getObject(){
return new Test();
}
So now you can create an object for this class from outside of it. Like the way...
Test t = Test.getObject();
Hence, a static method which returns the object of the class by executing its private constructor is called as FACTORY method.
I thought i will add some light to this post on what i know. We used this technique extensively in our recent android project. Instead of creating objects using new operator you can also use static method to instantiate a class. Code listing:
//instantiating a class using constructor
Vinoth vin = new Vinoth();
//instantiating the class using static method
Class Vinoth{
private Vinoth(){
}
// factory method to instantiate the class
public static Vinoth getInstance(){
if(someCondition)
return new Vinoth();
}
}
Static methods support conditional object creation: Each time you invoke a constructor an object will get created but you might not want that. suppose you want to check some condition only then you want to create a new object.You would not be creating a new instance of Vinoth each time, unless your condition is satisfied.
Another example taken from Effective Java.
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
This method translates a boolean primitive value into a Boolean object reference. The Boolean.valueOf(boolean) method illustrates us, it never creates an object. The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time.
Static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API.
Calendar.getInstance() is a great example for the above, It creates depending on the locale a BuddhistCalendar, JapaneseImperialCalendar or by default one Georgian.
Another example which i could think is Singleton pattern, where you make your constructors private create an own getInstance method where you make sure, that there is always just one instance available.
public class Singleton{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
A factory method a method that abstracts away the instantiation of an object. Generally factories are useful when you know that you need a new instance of a class that implements some interface but you don't know the implementing class.
This is useful when working with hierarchies of related classes, a good example of this would be a GUI toolkit. You could simply hard-code calls to the constructors for concrete implementations of each widget but if you ever wanted to swap one toolkit for another you'd have a lot of places to change. By using a factory you reduce the amount of code you would need to change.
One of the advantages that stems from Static factory is that that API can return objects without making their classes public. This lead to very compact API. In java this is achieved by Collections class which hides around 32 classes which makes it collection API very compact.
One of the advantages of the static factory methods with private constructor(object creation must have been restricted for external classes to ensure instances are not created externally) is that you can create instance-controlled classes. And instance-controlled classes guarantee that no two equal distinct instances exist(a.equals(b) if and only if a==b) during your program is running that means you can check equality of objects with == operator instead of equals method, according to Effective java.
The ability of static factory methods to return the same object from
repeated invocations allows classes to maintain strict control over
what instances exist at any time. Classes that do this are said to be
instance-controlled. There are several reasons to write
instance-controlled classes. Instance control allows a class to
guarantee that it is a singleton (Item 3) or noninstantiable (Item 4).
Also, it allows an immutable class (Item 15) to make the guarantee
that no two equal instances exist: a.equals(b) if and only if a==b. If
a class makes this guarantee, then its clients can use the == operator
instead of the equals(Object) method, which may result in improved
performance. Enum types (Item 30) provide this guarantee.
From Effective Java, Joshua Bloch(Item 1,page 6)
A static factory method is good when you want to ensure that only one single instance is going to return the concrete class to be used.
For example, in a database connection class, you may want to have only one class create the database connection, so that if you decide to switch from Mysql to Oracle you can just change the logic in one class, and the rest of the application will use the new connection.
If you want to implement database pooling, then that would also be done without affecting the rest of the application.
It protects the rest of the application from changes that you may make to the factory, which is the purpose.
The reason for it to be static is if you want to keep track of some limited resource (number of socket connections or file handles) then this class can keep track of how many have been passed out and returned, so you don't exhaust the limited resource.
Java implementation contains utilities classes java.util.Arrays and java.util.Collections both of them contains static factory methods, examples of it and how to use :
Arrays.asList("1","2","3")
Collections.synchronizedList(..), Collections.emptyList(), Collections.unmodifiableList(...) (Only some examples, could check javadocs for mor methods examples https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html)
Also java.lang.String class have such static factory methods:
String.format(...), String.valueOf(..), String.copyValueOf(...)
static
A member declared with the keyword 'static'.
factory methods
Methods that create and return new objects.
in Java
The programming language is relevant to the meaning of 'static' but not to the definition of 'factory'.

Can this Java singleton get rebuilt repeatedly in WebSphere 6?

I'm trying to track down an issue in our system and the following code worries me. The following occurs in our doPost() method in the primary servlet (names have been changed to protect the guilty):
...
if(Single.getInstance().firstTime()){
doPreperations();
}
normalResponse();
...
The singleton 'Single' looks like this:
private static Single theInstance = new Single();
private Single() {
...load properties...
}
public static Single getInstance() {
return theInstance;
}
With the way this is set to use a static initializer instead of checking for a null theInstance in the getInstance() method, could this get rebuilt over and over again?
PS - We're running WebSphere 6 with the App on Java 1.4
I found this on Sun's site:
Multiple Singletons Simultaneously Loaded by Different Class Loaders
When two class loaders load a class,
you actually have two copies of the
class, and each one can have its own
Singleton instance. That is
particularly relevant in servlets
running in certain servlet engines
(iPlanet for example), where each
servlet by default uses its own class
loader. Two different servlets
accessing a joint Singleton will, in
fact, get two different objects.
Multiple class loaders occur more
commonly than you might think. When
browsers load classes from the network
for use by applets, they use a
separate class loader for each server
address. Similarly, Jini and RMI
systems may use a separate class
loader for the different code bases
from which they download class files.
If your own system uses custom class
loaders, all the same issues may
arise.
If loaded by different class loaders,
two classes with the same name, even
the same package name, are treated as
distinct -- even if, in fact, they are
byte-for-byte the same class. The
different class loaders represent
different namespaces that distinguish
classes (even though the classes'
names are the same), so that the two
MySingleton classes are in fact
distinct. (See "Class Loaders as a
Namespace Mechanism" in Resources.)
Since two Singleton objects belong to
two classes of the same name, it will
appear at first glance that there are
two Singleton objects of the same
class.
Citation.
In addition to the above issue, if firstTime() is not synchronized, you could have threading issues there as well.
No it won't get built over and over again. It's static, so it'll only be constructed once, right when the class is touched for the first time by the Classloader.
Only exception - if you happen to have multiple Classloaders.
(from GeekAndPoke):
As others have mentioned, the static initializer will only be run once per classloader.
One thing I would take a look at is the firstTime() method - why can't the work in doPreparations() be handled within the singleton itself?
Sounds like a nasty set of dependencies.
There is absolutely no difference between using a static initializer and lazy initialization. In fact it's far easier to mess up the lazy initialization, which also enforces synchronization. The JVM guarantees that the static initializer is always run before the class is accessed and it will happen once and only once.
That said JVM does not guarantee that your class will be loaded only once. However even if it is loaded more than once, your web application will still see only the relevant singleton, as it will be loaded either in the web application classloader or its parent. If you have several web application deployed, then firstTime() will be called once for each application.
The most apparent things to check is that firstTime() needs to be synchronized and that the firstTime flag is set before exiting that method.
No, It won't create multiple copies of 'Single'. ( Classloader issue will be visited later )
The implementation you outlined is described as 'Eager Initialization' by in Briant Goetz's book - 'Java Concurrency in Practice'.
public class Single
{
private static Single theInstance = new Single();
private Single()
{
// load properties
}
public static Single getInstance()
{
return theInstance;
}
}
However, the code is not you wanted. Your code is trying to perform lazy-initialization after the instance is created. This requires all the client library to perform 'firstTime()/doPreparation()' before using it. You are going to rely on the client to do right thing which make the code very fragile.
You can modify the code as the following so there won't be any duplicate code.
public class Single
{
private static Single theInstance = new Single();
private Single()
{
// load properties
}
public static Single getInstance()
{
// check for initialization of theInstance
if ( theInstance.firstTime() )
theInstance.doPreparation();
return theInstance;
}
}
Unfortunately, this is a poor implementation of lazy initialization and this will not work in concurrent environment ( like J2EE container ).
There are many articles written about Singleton initialization, specifically on memory model. JSR 133 addressed many weakness in Java memory model in Java 1.5 and 1.6.
With Java 1.5 & 1.6, you have several choices and they are mentioned in the book 'Effective Java' by Joshua Bloch.
Eager Initialziation, like the above [EJ Item 3]
Lazy Initalization Holder Class Idiom [EJ Item 71]
Enum Type [EJ Item 3]
Double Checked Locking with 'volatile' static field [EJ Item 71]
Solution 3 and 4 will only work in Java 1.5 and above. So the best solution would be #2.
Here is the psuedo-implementation.
public class Single
{
private static class SingleHolder
{
public static Single theInstance = new Single();
}
private Single()
{
// load properties
doPreparation();
}
public static Single getInstance()
{
return SingleHolder.theInstance;
}
}
Notice that 'doPreparation()' is inside of the constructor so you are guarantee to get the properly initialized instance. Also, you are piggying back on JVM's lazy class loading and do not need any synchronization 'getInstance()'.
One thing you noticed that static field theInstance is not 'final'. The example on Java Concurrency does not have 'final' but EJ does. Maybe James's can add more color to his answer on 'classloader' and requirement of 'final' to guarantee correctness,
Having said that, there are a side-effect that with using 'static final'. Java compiler is very aggressive when it sees 'static final' and tries to inline it as much as possible. This is mentioned on a blog posting by Jeremy Manson.
Here is a simple example.
file: A.java
public class A
{
final static String word = "Hello World";
}
file: B.java
public class B
{
public static void main(String[] args) {
System.out.println(A.word);
}
}
After you compile both A.java and B.java, you change A.java to following.
file: A.java
public class A
{
final static String word = "Goodbye World";
}
You recompile 'A.java' and rerun B.class. The output you would get is
Hello World
As for the classloader issue, the answer is yes, you can have more than one instance of Singleton in multiple classloaders. You can find more information on wikipedia. There is also a specific article on Websphere.
The only thing I would change about that Singleton implementation (other than not using a Singleton at all) is to make the instance field final. The static field will be initialised once, on class load. Since classes are loaded lazily, you effectively get lazy instantiation for free.
Of course, if it's loaded from separate class loaders you get multiple "singletons", but that's a limitation of every singleton idiom in Java.
EDIT: The firstTime() and doPreparations() bits do look suspect though. Can't they be moved into the constructor of the singleton instance?
No - the static initialization of the instance will only ever be done once. Two things to consider:
This is not thread-safe (the instance is not "published" to main memory)
Your firstTime method is probably called multiple times, unless properly synchronized
In theory it will be built only once. However, this pattern breaks in various application servers, where you can get multiple instances of 'singleton' classes (since they are not thread-safe).
Also, the singleton pattern has been critized a lot. See for instance Singleton I love you, but you're bringing me down
This will get only loaded once when the class is loaded by the classloader.
This example provides a better Singleton implementation however, it's as lazy-loaded as possible and thread-safe.
Moreover, it works in all known versions of Java.
This solution is the most portable across different Java compilers and virtual machines.
public class Single {
private static class SingleHolder {
private static final Single INSTANCE = new Single();
}
private Single() {
...load properties...
}
public static Single getInstance() {
return SingleHolder.INSTANCE;
}
}
The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile and/or synchronized).
It's not mandatory for the single instance to be final (it's not a good idea at all indeed, because this will avoid you to switch it's behaviour using other patterns).
In the code below you can see how it gets instantiated only once (first time you call the constructor)
package date;
import java.util.Date;
public class USDateFactory implements DateFactory {
private static USDateFactory usdatefactory = null;
private USDateFactory () { }
public static USDateFactory getUsdatefactory() {
if(usdatefactory==null) {
usdatefactory = new USDateFactory();
}
return usdatefactory;
}
public String getTextDate (Date date) {
return null;
}
public NumericalDate getNumericalDate (Date date) {
return null;
}
}

Categories

Resources