Tony Scialo Tony Scialo - 4 months ago 11
Java Question

Public Class with private static variable of same class

Looking through some Java code the other day, I saw something I haven't seen before and am slightly confused on. Part of the code is shown below:

public class PreferredAlternateProxy {
...
private static PreferredAlternateProxy instance;
...

public static PreferredAlternateProxy getInstance(){
if(instance == null)
createInstance();

return instance;
}

private static synchronized void createInstance(){
if(instance == null)
instance = new PreferredAlternateProxy();
}
}


What is the purpose of declaring a static property of of the same class as the public class? In what situation is this useful?

What is the purpose of making the second method (createInstance()) synchronized?

Answer

There is something like Design Patterns that tell you the ways to efficiently write a code. The example you gave is called a Singleton. The purpose of this pattern is to create one and the only one instance of the class. It requires a:

  1. Private constructor(s) - that unables anyone from creating the instance of the class.
  2. Private static field - that will keep the generated instance in the memmory.
  3. Public static method - that is the "gatekeeper", whos job is to return the instance.

Example:

public class Singleton() {
    private static Singleton instance;

    private Singleton() {

    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

The above example is called Lazy Initialization, because the instance is not created until you call getInstance() for the first time.

Below example shows Early Initialization, which creates the instance right when the class loads into the memmory.

public class Singleton() {
    private static Singleton instance = new Singleton();

    private Singleton() {

    }

    public static Singleton getInstance() {
        return instance;
    }
}
Comments