Private Constructor initialized by a public method - java

I came cross a class with private constructor but the object is returned by another public method by call to the private constructor. What may be the advantage of such a construct when we could have made the constructor public?
public final class TokenTable {
static public int errorToken = 0;
static public int timesToken = 1;
static public int divToken = 2;
static public int plusToken = 11;
......
......
private final HashMap<String, Integer> keywordMap = new HashMap();
private final HashMap<String, Integer> operationMap = new HashMap();
private TokenTable() {
operationMap.put("*", timesToken);
operationMap.put("/", divToken);
operationMap.put("+", plusToken);
....
}
static public TokenTable getInstance() {
LexTokenTabInstance = new TokenTable();
return LexTokenTabInstance;
}
}

This is called the Factory pattern. Check out the description here - Factory Design Pattern.
There are several advantages:
you can have multiple named factory methods to create different flavors of the object which can allow for overloading with the same set of parameter types
you can return a singleton if appropriate or maybe return one of a cached set of instances
if don't need to use new
when using generics, the generic type is inferred by the compiler so don't need to use the <> operator
you can return an interface instead of a concrete class
allows for pre-constructor initialization (for example if init must be done prior to calling base class constructor)
To be clear, the above example it seems that it was done just as a "good practice" since none of the above capabilities was used (other than you don't have to use "new").

This is called a factory method. A factory method has many advantages over a constructor:
it has a name (and multiple factory methods may have different names)
it allows returning a cached instance instead of a new instance
it allows returning a subclass instance instead of the actual class
etc.

The main advantage is that no one can create an instance, but using static getInstance method.
This way you can make sure only one instance is created, just as Singelton design pattern

The primary reason for hiding a constructor of a class is to control how objects of that class are created. A common example of this is in the Singleton pattern, where only one object of a class is instantiated.
In order to police this, the user accesses a static method which will access the private constructor if the object isn't created, or else return a reference to the already created object:
public class SingletonDemo {
private static volatile SingletonDemo instance = null;
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null) {
synchronized (SingletonDemo.class){
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
}
For other examples, look at Factory patterns in general: http://en.wikipedia.org/wiki/Factory_method_pattern

If you do not want to protect creation of multiple instance outside the class then you can create private constructor.
This is helpful creating a single instance.
You can do it like(Eager loading):
private static final TokenTable tokenTable = new TokenTable();
static public TokenTable getInstance() {
return tokenTable;
}
Or, you can do it like(Lazy loading):
private static TokenTable tokenTable;
static public TokenTable getInstance() {
if(null == tokenTable){
tokenTable = new TokenTable();
}
return tokenTable;
}

Related

Singleton Pattern Recommended Method

Case 1:
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton() {
...
}
}
Case 2:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
...
}
public static Singleton getInstance() {
return INSTANCE;
}
}
Is the second method the recommended way to implement the Singleton design pattern, because I have never seen the first one in any example for Singleton pattern.
Without going into all the stuff about singletons being an antipattern (but you should read up on it!), the currently best way to make a singleton in Java is to use an enum.
public enum Singleton {
INSTANCE;
}
The reason this is better is because the JVM guarantees that only one instance of the enum (per classloader) will exist at any time. It is thread safe, and you cannot use reflection to create another instance of the singleton.
Enum-values are also lazily instantiated, so you won't create the singleton before you access Singleton.INSTANCE the first time.
The best way to make a singleton is to use Enum.
public enum Foo {
INSTANCE;
}
What is an efficient way to implement a singleton pattern in Java?
In your example, case 1 is more simple, so it's better.
But just wonder what happen if your constructor function is more complicated with some parameters. At this time, you really need some thing like this:
public class Singleton {
private static final Singleton INSTANCE;
private Singleton(string a, string b, string c) {
...
}
public static Singleton getInstance(string a, string b, string c) {
if (INSTANCE != null) { //note in multiple thread env, need add synchronize here.
......
}
return INSTANCE;
}
}
The first process of creating Singleton object created the instance of Singleton class even before it is being used and that is not the best practice to use.
Also the same problem exists in second implementation.
My preferred way of singleton instance creation:
private static final Singleton INSTANCE = null;
public static Singleton getInstance(){
if(INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
}
Above implementation of Singleton instance creation is okay in single threaded environment but in case of multi-threaded environment two threads may access if block at same time so they will have different instances. This could be solved as below:
private static final Singleton INSTANCE = null;
public static Singleton getInstance(){
if(INSTANCE == null){
synchronized (Singleton.class) {
if(INSTANCE == null){
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
Hope this helps.
This how I implement singleton with enum
import static collections.concurrancy.ConcurrentHashMapInstanceEnum.STAFF;
public enum ConcurrentHashMapInstanceEnum {
STAFF;
private ConcurrentHashMap<Integer,Person> concurrentHashMap = null;
private ConcurrentHashMapInstanceEnum() {
concurrentHashMap = new ConcurrentHashMap(10, 5f, 4);
}
public ConcurrentHashMap getConcurrentHashMap() {
return concurrentHashMap;
}
}
and this is how to reach in a thread...
staffList = STAFF.getConcurrentHashMap()
Yes Obviously the second method is preferred way to implement Sigleton pattern , Inside getInstance() you have to check if instance is already created then return the same and Only create new instance if there is No instance of the class.
Also Make getInstance method as static method.

Java: why a constructor has access modifier?

For example a class:
//class1
class A {
private A() { } // why would I make it private?
public A(int) { } //why isn't it implicitly public?
}
//class2
class B {
public static void main(String[] args) {
//A a = new A();
}
}
A constructor instantiates a class so why it has the access modifier?
Is there a case when we have to declare a constructor private?
A constructor instantiates a class so why it has the access modifier?
The modifier can be used so you control where the object can be constructed.
Is there a case when we have to declare a constructor private?
Say you have a factory method like
class A {
private A(int n) { }
public static A create(int n) {
return new A(n);
}
}
or you have a shared constructor which should be called directly.
class B {
public B(int n) {
this(n, "");
}
public B(String str) {
this(0, str);
}
private B(int n, String str) { }
}
or you have a Singleton
final class Singleton {
Singleton INSTANCE = new Singleton();
private Singleton() { }
}
however I prefer to use an enum which has a private constructor.
enum Singleton {
INSTANCE;
}
or you have a Utility class
final class Utils {
private Utils() { /* don't create one */ }
public static int method(int n) { }
}
however I prefer to use an enum in this case
enum Utils {
/* no instances */;
public static int method(int n) { }
}
Note: if you use a private constructor on a final class you can still create instances using nested classes, or reflection. If you use an enum you can't create an instance as easily/accidentally.
Warning: You can create instances of an enum using Unsafe
Note in enum the constructor has to be private
class BuySell {
BUY(+1), SELL(-1);
private BuySell(int dir) { }
}
You don't have to make it private explicitly as this is the default.
The private modifier when applied to a constructor works in much the same way as when applied to a normal method or even an instance variable. Defining a constructor with the private modifier says that only the native class (as in the class in which the private constructor is defined) is allowed to create an instance of the class, and no other caller is permitted to do so. There are two possible reasons why one would want to use a private constructor – the first is that you don’t want any objects of your class to be created at all, and the second is that you only want objects to be created internally – as in only created in your class.
Uses of private construtor:-
1) Private constructors can be used in the singleton design pattern
2) Private constructors can prevent creation of objects
This might also help Can a constructor in Java be private? the use cases of private constructor
Constructor are not responsible for Creating a object of a Class, these constructor are only responsible for initialize the member variables only.
There are various Reason behind this. One of the most popular reason behind this is design-Pattern.
//class1
class A {
private A() { } // why would I make it private?
}
why make private Constructor ?
If you want to make a Class singleton then your constructor must be private. then only it is possible to make a Class a Singleton.

Different kind of singleton pattern

I'm studying basic software design pattern.
The basic implementation of singleton classes are written like this:
public class MyObject{
private volatile static MyObject obj;
private MyObject(){/*Do some heavy stuff here*/}
public static synchronized MyObject getInstance(){
if(obj==null)
obj=new MyObject();
return obj;
}
}
But as I have undestood calling synchronized methods can be heavy.
I while back I red a book the introduced this kind of implementation of Singleton class:
public class MyObjectHolder {
private volatile static Supplier<MyObject> myObjectSupplier = () -> createMyObj();
//myObjectSupplier is changed on the first 'get()' call
public static MyObject getMyObject(){
return myObjectSupplier.get();
}
private static synchronized MyObject createMyObj(){
class MyObjectFactory implements Supplier<MyObject> {
private final MyObject clockTimer = new MyObject();
public MyObject get() { return clockTimer; }
}
if(!MyObjectFactory.class.isInstance(myObjectSupplier)) {
myObjectSupplier = new MyObjectFactory();
}
return myObjectSupplier.get();
}
public static class MyObject{
private MyObject(){
/*Do some heavy stuff here*/
}
public void someMethod(){
/* ... */
}
}
}
...
{
/*In main MyObject instantiation*/
MyObjectHolder.MyObject obj = MyObjectHolder.getMyObject();
}
Now after the first call for 'createMyObj()' has been has been finished, there is no heavy burden of synchronized method calling and the is no if check neither.
Do you think there is something wrong with this kind of implementation?
ps. MyObject does not have to be an inner class of MyObjectHold but I thought it looked nice.
[UPDATED] Another solution that is called Initialization on Demand Holder idiom :
public class SingletonObject {
private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger();
private static final AtomicInteger INVOKE_COUNT = new AtomicInteger();
private static final class LazyHolder {
private static final SingletonObject INSTANCE = new SingletonObject();
}
private SingletonObject() {
System.out.println("new SingletonObject");
INSTANCE_COUNT.getAndIncrement();
}
public static SingletonObject getInstance() {
INVOKE_COUNT.getAndIncrement();
return LazyHolder.INSTANCE;
}
public static int getInstanceCount() {
return INSTANCE_COUNT.get();
}
public static int getInvokeCount() {
return INVOKE_COUNT.get();
}
}
to prove that it's thread-safe :
public static void main(String[] args) throws Exception {
int n = 1000;
List<Callable<SingletonObject>> invokers = new ArrayList<>();
for (int i = 0; i < n; i++) {
invokers.add(SingletonObject::getInstance);
}
ExecutorService es = Executors.newFixedThreadPool(n);
es.invokeAll(invokers);
es.shutdown();
System.out.println("Number of Instances = " + SingletonObject.getInstanceCount());
System.out.println("Number of Invokes = " + SingletonObject.getInvokeCount());
}
Output :
new SingletonObject
Number of Instances = 1
Number of Invokes = 1000
EDIT (after #Holger's comment) :
the use of the Nested Holder Class is somewhat necessary to Lazily Initialize the SingletonObject.
public class SingletonObject {
private static final SingletonObject INSTANCE = new SingletonObject();
private SingletonObject() {
System.out.println("new SingletonObject");
}
public static SingletonObject getInstance() {
return INSTANCE;
}
public static void anotherStaticMethod() {
System.out.println("I don't need the SingletonObject Instance...");
}
}
So what happens if someone invokes the anotherStaticMethod()?
new SingletonObject
I don't need the SingletonObject Instance...
UPDATE :
The page at WIKIPEDIA says :
The implementation of the idiom relies on the initialization phase of execution within the Java Virtual Machine (JVM) as specified by the Java Language Specification (JLS). When the class SingletonObject is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class definition LazyHolder within it is not initialized until the JVM determines that LazyHolder must be executed. The static class LazyHolder is only executed when the static method getInstance is invoked on the class SingletonObject, and the first time this happens the JVM will load and initialize the LazyHolder class. The initialization of the LazyHolder class results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class SingletonObject. Since the class initialization phase is guaranteed by the JLS to be serial, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization. And since the initialization phase writes the static variable INSTANCE in a serial operation, all subsequent concurrent invocations of the getInstance will return the same correctly initialized INSTANCE without incurring any additional synchronization overhead.
This gives a highly efficient thread-safe "singleton" cache, without synchronization overhead; benchmarking indicates it to be far faster than even uncontended synchronization. However, the idiom is singleton-specific and not extensible to pluralities of objects (e.g. a map-based cache).
Also keep an eye on this.
The easiest way to implement the Singleton pattern in java is to simply make the class an enum instead:
public enum MyObject{
Obj;
MyObject(){/*Do some heavy stuff here*/}
}
Obj is guaranteed by the specification to only be created once on the first use of it.
Singleton pattern breaks Single Responsibility Principle (SRP) - because the class has to do two things:
It's primary task
Enforcing singleton-ness.
Your second approach is trying to delegate this 'Enforcing singleton-ness' to a separate class - following SRP. If you are using a dependency injection framework like spring, you can achieve the same effect by only defining MyObject class and declaring this class with a 'singleton' scope in the spring context.

Implement singleton with static access modifier in Java

Example class with singleton design pattern.
class Singleton {
private static Singleton instance;
private int x;
private Singleton() {
x = 5;
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
public void doSomething() {
System.out.println("Hello");
}
}
I'm just wondering can I create this class with same variables and methods declared as static. Is it same as the singleton?
Singleton should be considered only if all three of the following criteria are satisfied:
Ownership of the single instance cannot be reasonably assigned
Lazy initialization is desirable
Global access is not otherwise provided for
Yes, It is the same.
If you really need to implement a singelton pattern I would recommend using an enum:
public enum MySingelton{
INSTANCE;
private final String[] variable = new String[]{"test", "test2};
public void randomFunction(){
}
}
Call it with:
MySingelton.INSTANCE.randomFunction();
With an enum implementation it's guaranteed that only one instance is created and that it's available all the time. Also it's possible to serialize and deserialize the singelton without creating multiple copies of it.
More information can be found here:
What is an efficient way to implement a singleton pattern in Java?
http://www.drdobbs.com/jvm/creating-and-destroying-java-objects-par/208403883?pgno=3
Since the purpose of the singleton pattern is to ensure that a single instance of a class exists, yes, you could use static members to achieve the same effect.
So instead of
public class Singleton {
private static Singleton theInstance = new Singleton();
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
return theInstance;
}
}
you could do
public class FakeSingleton {
private static int aVar = 10;
public static void aMethod() {
System.out.println(aVar);
}
}
and have exactly the same functionality (instead of Singleton.getInstance().aMethod() you would write FakeSingleton.aMethod()).
Using the singleton pattern can be advantageous if you want lazy initialization, so that the singleton is only initialized when it is first needed, as follows:
public class Singleton {
private static Singleton theInstance = null;
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
if (theInstance == null) {
theInstance = new Singleton();
}
return theInstance;
}
}
(Note that the above is not thread-safe, in multithreaded code you will need to add synchronization.)

Singleton instantiated with this

I have an assignment for school where I have to spot patterns in a certain given project. All is well (well, relatively..) but it seems that most patterns I find are some sort of variation. The singleton I had to find is no different.
The code is given below. The strange thing about this is that this class does not seem to instantiate with the following constructor, as one would expect:
public Singleton() {
if (singleton == null) {
singleton = new Singleton();
}
}
However, it is instatiated with this (as you can see in the original code below)? In my understanding this creates some sort of static singleton? I debugged and saw indeed that the first time the constructor is called by
Singleton x = new Singleton();
x.Print();
, it is indeed null. And this is a Singleton instance. However, shouldn't there be
private static Singleton singleton = new Singleton();
on top of the class instead of singelton = this;?
public class Singleton {
private static Singleton singleton;
public static Singleton getDefault() {
return singleton;
}
/**
* The constructor.
*/
public Singleton() {
if (singleton == null) {
singleton = this;
}
}
public void Print()
{
System.out.println("I'm a singleton!");
}
}
I'm pretty sure it is indeed a singleton, it's just of the type I have never seen and I don't get reasoning behind it, that's what I'm basicly asking.
There is generally two approaches to creating a Singleton class, both are based on keeping the constructor private.
The first approach:
public class Singleton
{
public static final Singleton INSTANCE = new Singleton();
private Singleton{...}
}
You create an instance like this: Singleton single = Singleton.INSTANCE;
The second approach:
public class Singleton
{
private static final Singleton INSTANCE = new Singleton();
private Singleton(){...}
public static Singleton getInstance(){ return INSTANCE; }
}
In this case, you create an instance like this: Singleton single = Singleton.getInstance();
The getInstance() method is then regarded as a public factory method.
As you can see, in both cases the new keyword is definitely used to create a single instance of the class, but because of the pattern used, there can only be one instance and no more. You don't need to use the "this" keyword.
Hope this helps.
Your code has not followed the Singleton pattern. I have shown below a class following the Singleton pattern. this refers to the current object instance. When you initialize the singleton reference with this inside constructor, it calls the default (no-args) constructor and assigns it back to the this reference and then it is assigned to singleton class member variable
public class Singleton {
private static Singleton singleton;
public static Singleton getDefault() {
if (singleton == null)
singleton = new Singleton();
return singleton;
}
/**
* The constructor.
*/
private Singleton() {
System.out.println(singleton);
if (singleton == null) {
/*this will call a default constructor
*and instantiate Singleton object
*/
singleton = this;
}
}
public void Print() {
System.out.println("I'm a singleton!");
}
public static void main(String[] args) {
Singleton singleton = Singleton.getDefault();
System.out.println(singleton.Print());
}
}
Hope you can understand!
I think you are confusing the meaning or this. this is not instantiating the class, this references the newly created instance. Then whenever someone calls your constructor a new instance is created (and returned) no matter you store in private static Singleton singleton; or not.
As well said #dic19 you must make your constructor private for preventing more than one instance to exist.
If the point is not to modify the code as you said, then the point is to report that this class is NOT a singleton.
You can check debugging:
Singleton x = new Singleton();
Singleton x1 = new Singleton();
Singleton x2 = new Singleton();
You will see all three are different instances, being Singleton.getDefault() simply the first you created.
If we use singletone we do not need to create instance for use. Because when we are creating singletone then we are creating new instance if not created.
Take a look of below code :
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getSingleton() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public void testSingleTone(){
System.out.println("test");
}
public static void main(String[] args){
Singleton.getSingleton().testSingleTone();
}
}

Categories