Why do we need a private constructor at all? - java

This answer says that we can't instantiate more than one object at a time via private constructors. I have modified the code which does just the opposite:
class RunDatabase{
public static void main(String[] args){
Database db = Database.getInstance("hello");//Only one object can be instantiated at a time
System.out.println(db.getName());
Database db1 = Database.getInstance("helloDKVBAKHVBIVHAEFIHB");
System.out.println(db1.getName());
}
}
class Database {
//private static Database singleObject;
private int record;
private String name;
private Database(String n) {
name = n;
record = 0;
}
public static synchronized Database getInstance(String n) {
/*if (singleObject == null) {
Database singleObject = new Database(n);
}
return singleObject;*/
return new Database(n);
}
public void doSomething() {
System.out.println("Hello StackOverflow.");
}
public String getName() {
return name;
}
}
And as expected both the strings are being printed. Did I miss something?

We can't instantiate more than one object at a time via private constructors.
No, we can. A private constructor only avoids instance creation outside the class. Therefore, you are responsible for deciding in which cases a new object should be created.
And as expected both the strings are being printed. Did I miss something?
You are creating a new instance every time the getInstance method is called. But your commented code contains a standard lazy initialization implementation of the singleton pattern. Uncomment these parts to see the difference.
Other singleton implementations you can look over here.

Private constructors are used to stop other classes from creating an object of the "Class" which contains the private constructor.
This is done to provide the singleton pattern where only a single instance of the class is used.
The code that you have mentioned is supposed to create just one instance of the class and use that instance only to perform all the operations of that class. But you have modified the code which violates the singleton design pattern.

Why do we need a private constructor at all?
Basically 3 reasons:
if you don't want the user of the class creates an object directly, and instead use builders or similars,
if you have a class defined for constants only, then you need to seal the class so the JVM don't create instances of the class for you at runtime.
singletons

Related

singleton public static final

I've been wondering about singletons in Java. By convention, a singleton is set up something like this:
private static MyClass instance = null;
public static MyClass getInstance(){
if (instance == null){
instance = new MyClass();
}
return instance;
}
private MyClass(){}
Recently I've switched to using the following:
public static final MyClass instance = new MyClass();
private MyClass(){}
This is a lot shorter, faster as there's no null-check, and typing MyClass.instance feels nicer to me than typing MyClass.getInstance(). Is there any reason why the second is not the mainstream way to do this?
The first version creates the instance the first time it is actually needed, while the second (the shorter) runs the constructor as soon as the class is initialized
A class or interface type T will be initialized immediately before the
first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant
variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10)
lexically nested within T (§8.1.3) is executed. [...]
Invocation of certain reflective methods in class Class and in
package java.lang.reflect also causes class or interface initialization.
The initialization upon first usage is a performance improvement that may speed up the startup of the application if the code in the constructor makes expensive operations. On the other hand, the second version is straightforward to read and is automatically thread-safe.
Anyway, the state of the art is not creating singleton in either ways: for a bunch of KB you can get dependency injection libraries that make it working for you, and also handle more complex scenarios (for example look at Spring and AOP-backed injection).
Note: the first version is not thread safe in the pasted snippet
The way you have first described is known as lazy instantiation, i.e the object will only be created when it is first called. This method is not thread-safe as it is possible for a second thread to create a second instance.
If you read the following book:
Effective Java by Joshua Bloch
He explains that the best implementation of the singleton pattern is through the use of an Enum :
public enum Singleton {
INSTANCE;
public void doSomething() {
...
}
}
Then you would call your singleton through the Enum as follows:
public class Test {
public void test(){
Singleton.INSTANCE.doSomething();
}
}
This fits nicely with what you are saying in terms of it looks nicer and shorter to write but also guarantees there can never be a second instance.
I can think of two reasons:
The first is Encapsulation: you might have second thoughts about how and when your singleton is initialized, after your class has been exposed to client code. And an initialization method gives you more freedom as to changing your strategy later on. For example you might change your mind and decide to use two different constructors instead of one, according to another static variable's value at runtime. With your solution you're bound to using just one constructor at the time your class is loaded into memory, whereas with getInstance() you can change the initialization logic without affecting the interface to the client code.
The second is Lazy Initialization : with the conventional singleton implementation the MyClass object is loaded into memory only when needed by the client code for the first time. And if the client code doesn't need it at all, you save on the memory allocated by your application. Note that whether your singleton is needed or not might not be certain until the program runs. For example it might depend on the user interaction with the program.
However the Lazy Initialization is not something you might necessarily want. For example if you're programming an interactive system and the initialization of your singleton is time consuming, it might actually be better to initialize it when the program is loading rather than when the user is already interacting with it, cause the latter might cause a latency in your system response the first time getInstance() is called. But in this case you can just have your instance initialized with the public method as in:
private static MyClass instance = getInstance();
The best way to synchronize the threads is using Double Checked (to ensure that only one thread will enter the synchronized block at a time and to avoid obtaining the lock every time the code is executed).
public class DoubleCheckLocking {
public static class SearchBox {
private static volatile SearchBox searchBox;
// private attribute of this class
private String searchWord = "";
private String[] list = new String[]{"Stack", "Overflow"};
// private constructor
private SearchBox() {}
// static method to get instance
public static SearchBox getInstance() {
if (searchBox == null) { // first time lock
synchronized (SearchBox.class) {
if (searchBox == null) { // second time lock
searchBox = new SearchBox();
}
}
}
return searchBox;
}
}
Reflection: Reflection can be caused to destroy singleton
property of singleton class, as shown in following example:
// Java code to explain effect of Reflection
import java.lang.reflect.Constructor;
// Singleton class
class Singleton
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
}
public class GFG
{
public static void main(String[] args)
{
Singleton instance1 = Singleton.instance;
Singleton instance2 = null;
try
{
Constructor[] constructors =
Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors)
{
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
instance2 = (Singleton) constructor.newInstance();
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("instance1.hashCode():- "
+ instance1.hashCode()); //366712642
System.out.println("instance2.hashCode():- "
+ instance2.hashCode()); //1829164700
}
}

How to access an specific object from other object without passing pointer to that object in java?

I have an object say A that loads some data from disk and it takes a bit long time to load. Many of other objects need its methods and data so I don't want neither any time I need it create a new one nor passing it through class constructor. Is there any way to create an instance of the class A only once at the beginning of the running project and all the other objects have access to the object A?
I apologize if my question is duplicated but I don't have any idea about what keywords relate to this question to find related questions.
In that case you are dealing with the Singleton Design Pattern you should declare youre class like this:
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
And then you can use it as intended.
In fact the approach here is to use static members like this:
public class Vehicle {
private static String vehicleType;
public static String getVehicleType(){
return vehicleType;
}
}
The static modifier allows us to access the variable vehicleType and the method getVehicleType() using the class name itself, as follows:
Vehicle.vehicleType
Vehicle.getVehicleType()
Take a look at Java static class Example for further information.
Sure. The design pattern is called a singleton. It could look like this:
public class Singleton {
private static Singleton instance;
private Singleton () {}
/*
* Returns the single object instance to every
* caller. This is how you can access the singleton
* object in your whole application
*/
public static Singleton getInstance () {
if (Singleton.instance == null) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
All objects can use the singleton by calling Singleton.getInstance()

How to make sure that there is just one instance of class in JVM?

I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a single point, but I don't know if it is possible.
I can only think of a way to count instances of a class and destroy all instance after first is created.
Is this a right approach? If not, is there any other way?
Use the singleton pattern. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance,
public class Singleton {
private static Singleton instance;
/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}
/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}
/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public String demoMethod() {
return "demo";
}
}
Note that the method of using “lazy evaluation” in the getInstance() method (which
is advocated in Design Patterns), is not necessary in Java because Java already uses “lazy
loading.” Your singleton class will probably not get loaded unless its getInstance()
is called, so there is no point in trying to defer the singleton construction until it’s needed
by having getInstance() test the singleton variable for null and creating the singleton
there.
Using this class is equally simple: simply get and retain the reference, and invoke methods on it:
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}
Some commentators believe that a singleton should also provide a public final
clone() method that just throws an exception, to avoid subclasses that “cheat” and
clone() the singleton. However, it is clear that a class with only a private constructor
cannot be subclassed, so this paranoia does not appear to be necessary.
That's the well known Singleton pattern: you can implement this as follows:
public class SingletonClass {
//this field contains the single instance every initialized.
private static final instance = new SingletonClass();
//constructor *must* be private, otherwise other classes can make an instance as well
private SingletonClass () {
//initialize
}
//this is the method to obtain the single instance
public static SingletonClass getInstance () {
return instance;
}
}
You then call for the instance (like you would constructing a non-singleton) with:
SingletonClass.getInstance();
But in literature, a Singleton is in general considered to be a bad design idea. Of course this always somewhat depends on the situation, but most programmers advice against it. Only saying it, don't shoot on the messenger...
There is a school of thought that considers the Singleton pattern to in fact be an anti-pattern.
Considering a class A that you only wish to have one of, then an alternative is to have a builder or factory class that itself limits the creation of the number of objects of Class A, and that could be by a simple counter.
The advantage is that Class A no longer needs to worry about that, it concentrates on its real purpose. Every class that uses it no longer has to worry about it being a singleton either (no more getInstance() calls).
You want the Singleton pattern. There is an excellent discussion of how to implement this properly. If you do this right, there will only ever be one instance of the class.
Essentially what you are going to do is create a class, hold a single instantiated object of that class at the static level, and provide a static accessor to get it (getInstance() or similar). Make the constructor final so people can't create their own instances out of the blue. That link above has plenty of great advice on how to do this.
Use enum. In Java enum is the only true way to create a singleton. Private constructors can be still called through reflection.
See this StackOverflow question for more details:
Implementing Singleton with an Enum (in Java)
Discussion:
http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html
I can only think of a way to count instances of a class and destroy all instance after first is created. Is this a right approach ? If not, is there any other way ?
The correct technical approach is to declare all of the constructors for the class as private so that instances of the class can only be created by the class itself. Then you code the class only ever create one instance.
Other Answers show some of the ways to implement this, according to the "Singleton" design pattern. However, implementing a singleton like this has some drawbacks, including making it significantly harder to write unit tests.
I prefer lazy singleton class, which overrides readResolve method.
For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.
Lazy singleton using /Initialization-on-demand_holder_idiom:
public final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
Key notes:
final keyword prohibits extension of this class by sub-classing
private constructor prohibits direct object creation with new operator in caller classes
readResolve prohibits creation of multiple instances of class during object de-serialization
For that you need to use singleton pattern, I am just posting a demo code for that that may useful for your understanding.
E.g: If I want only one object for this Connect class:
public final class Connect {
private Connect() {}
private volatile static Connect connect = null;
public static Connect getinstance() {
if(connect == null) {
synchronized (Connect.class) {
connect = new Connect();
}
}
return connect;
}
}
Here the constructor is private, so no one can use new keyword to make a new instance.
class A{
private A(){
}
public static A creator(A obj){
A ob=new A();
return ob;
}
void test(){
System.out.println("The method is called");
}
}
class Demo{
public static void main(String[] args){
A ob=null;
ob=A.creator(ob);
ob.test();
}
}

Why is it mandatory to have private Constructor inside a Singleton class

This is my singleton class for obtaining the database connection.
I have a question here: why it compulsory to have a private constructor inside a singleton class (as throughout my entire application I am calling this class only once) and as one instance of a class can be achieved using the static method?
Can this private constructor can be avoided, or is it mantadatory?
public class ConnPoolFactory {
private static DataSource dataSource;
private static Connection connection;
private ConnPoolFactory() {
System.out.println(" ConnPoolFactory cons is called ");
}
public static synchronized Connection getConnection() throws SQLException {
try {
if (connection == null) {
Context initContext = new InitialContext();
Context envContext = (Context) initContext
.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/Naresh");
connection = dataSource.getConnection();
} else {
return connection;
}
} catch (NamingException e) {
e.printStackTrace();
}
return connection;
}
}
Otherwise everyone can create an instance of your class, so it's not a singleton any more. For a singleton by definition there can exist only one instance.
If there no such a private constructor, Java will provide a default public one for you. Then you are able to call this constructor multiple times to create several instances. Then it is not a singleton class any more.
If you don't need lazy initiation:
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
is the best way, because is thread safe.
The Singleton pattern typically includes a non-public constructor, for two reasons. A constructor has to exist because if there's no constructor at all, a public default constructor is included. If you have a public constructor, though, people can just make their own singletons at will (which someone inevitably will, meaning there can be more than one).
It doesn't have to be private, though. In fact, as i heard it, the Singleton pattern as specified by the GoF mentions a protected constructor, for some odd reason. Something about inheritance, i hear, but singletons and inheritance do not play well together at all anyway.
It's even possible to have a public constructor, as long as it can detect whether an instance already exists and throw an exception or something if it does. That'd be enough to guarantee singleness. But it's rather uncommon, because doing it that way complicates things by providing two apparent ways to acquire an instance -- only one of which will actually work. If you don't want outside code to be able to create a second instance, why should a constructor be part of the public interface?
For the singleton pattern you use an private constructor to ensure that no other instances can be created, otherwise it wouldn't be a singleton.
A static class is different from a singleton in that a a singleton class enforces that there is always at most one instance. A static class has no instances, and is just a bundle of static functions and static data.
So for a Singleton class, i.e. one with at most one instance, then a private constructor is required.
In your example, it looks like the Singleton class fits more than the static class- because of the connection and dataSource members. Make those members private, your constructor private and provide static methods that reference a static ConnPoolFactory instance. If instance is null, create a new one, otherwise just use it.
For singletons and utilty classes you can use an enum which is a final class and implicitly defines a private constructor.
enum Singleton {
INSTANCE
}
or
enum Utility {;
}
In your example above you have a utility class because you have no instance fields, methods and don't create an instance.
The comment as you said that If I am complete owner of my application and I will never commit mistake of creating instance of singleton class directly using the public constructor but will use the static method for getting it. But in real world, often application switch hands between multiple developers. If the new developer is not aware that you want only one instance of the class in the application, he/she may accidently create another one by using the public constructor.
It is mandatory. Your code may be fine, but others can use this code and instantiate another object, or you might do it by accident. This way is safe.
Singleton def:
Ensure the only one object need to create for the entire main stack (per main class).
If you want to satisfy above statement then we should give constructor as a private. Actually through singleton we are getting ref not object that's why it is not mandatory then we can create object in other classes but we can't access reference (Constructor as public).
Ex:
public class SingleTon {
private static SingleTon s;
public SingleTon() {}
public static SingleTon getInstance() {
if (s == null) {
s = new SingleTon();
System.out.println("ho ho");
} else{
return s;
}
return s;
}
}
Other class:
public class Demo {
public static void main(String[] args) {
//SingleTon s=SingleTon.getInstance();
SingleTon s11=new SingleTon();
SingleTon s12=new SingleTon();
s11.getInstance();
s12.getInstance();
}
}
Output:
ho ho

ThreadLocal with Singletons

I am working on the following piece of code. Two threads requiring their own instance of a singleton. Thread Local is an obvious solution to this. However I am still facing issues running the threads with their own local copy. I have an example of the scenario in a couple of java classes.
public class Singleton1 {
private int i = 0;
private static Singleton1 instance;
private Singleton1() {
}
public static final Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
public int increment() {
return i++;
}
}
public class Holder1 {
private final Singleton1 instance;
public Holder1() {
ThreadLocalSingleton1 singleton1 = new ThreadLocalSingleton1();
instance = singleton1.get();
}
public int increment() {
return instance.increment();
}
private class ThreadLocalSingleton1 extends ThreadLocal<Singleton1> {
#Override
protected Singleton1 initialValue() {
return Singleton1.getInstance();
}
}
}
public class HolderTest {
/**
* #param args
*/
public static void main(String[] args) {
HolderTest test = new HolderTest();
HolderThread thread1 = test.getHolderThread("thread1");
HolderThread thread2 = test.getHolderThread("thread2");
thread1.run();
thread2.run();
}
public HolderThread getHolderThread(String name) {
return new HolderThread(name);
}
private class HolderThread implements Runnable {
String name;
Holder1 holder1 = new Holder1();
public HolderThread(String name) {
this.name = name;
}
#Override
public void run() {
while (true) {
System.out.println(name + " " + holder1.increment());
}
}
}
When the ThreadLocal wrappers call getInstance on the Singleton classes I do not get a new instance each time? How do I make this work for my purposes?
The code above is a simple version of the actual code I am working with. I have Singleton classes which I cannot change from being singletons. I am creating a test client which needs to run as a single process but with many threads. Each of these threads needs to have its own instance of these singletons.
Your target class shall not be singleton, but you must access it just using the ThreadLocal, and creating a new instance if ThreadLocal instance is empty (doesn't hold a reference to an instance of your target object).
Another solution is to make your Target class singleton, and hold its state in ThreadLocal variables.
You seem to be painted into a corner.
On the one hand, you have an existing codebase that you need to test and that code uses (genuine, properly implemented) singleton objects. In particular, the declaration of the Singleton1() constructor as private in your examplar class Singleton1 makes it impossible to declare a subclass.
On the other hand, your testing requires you to write a client with lots of these Singleton1 instances.
On the face of it, that is impossible. There is no way to make two instances of the Singleton1 class in the JVM, and there is no way to declare a (compilable / loadable) subclass of Singleton1.
This is per design; i.e. it is what the designer of the Singleton1 class intended. (And if not, then the answer is to change Singleton1 to make it easier to test. For example, by making the Singleton1 constructor not private so that multiple instances can be created for test purposes. )
(For instance, your current attempt at implementing ThreadLocalSingleton1 fails because the Singleton1.getInstance() returns the global instance of Singleton1. No matter what you do, there is no way to create any other instance of the Singleton1 class.)
However, I can think of two workarounds for your particular use-case.
I am writing a test client which needs to run as as single java process. The test client is used for load testing will have X threads accessing a server using a core project (that I cannot change too much) which has many singletons. The singletons hold state which will be required per thread.
Here are the workarounds:
Instead of running one JVM with N instances of your test thread, run N separate JVMs each with a single test thread. Each JVM / test thread can have its own instance of Singleton.
Have each of your test threads create a new classloader, and use that classloader to dynamic load the Singleton1 class and everything with a direct or indirect static dependency on the Singleton1 type. The idea is for each classloader to load its own copy of the Singleton1 class. Since each copy will be a distinct type1, it will have its own private static Singleton1 instance variable.
Note that these workarounds do provide not "thread-local" instances of your Singleton1 class. That is both technically impossible ... and a contradiction of the definition of singleton.
In both cases you have true singleton instances, but they are instances of different Singleton1 types ... for different reasons.
1 - At runtime, the type of a class instance is conceptually a pair consisting of the fully qualified name of the class and the identity of the classloader that loaded the class. If the same bytecode file is loaded by different classloaders, then you get different runtime types.
Do you mean something like this?
private static final ThreadLocal<AtomicInteger> COUNTER = new ThreadLocal<AtomicInteger>() {
#Override
protected AtomicInteger initialValue() {
return new AtomicInteger();
}
};
public static int incrementAndGet() {
return COUNTER.get().incrementAndGet();
}
Please, take a look at the ThreadLocal working example below:
public class YourDataHolder {
private static ThreadLocal dataVariable = new ThreadLocal();
private static YourDataHolder dataHolderVar;
private YourDataHolder() { }
public void storeDataToThreadLocal (String userName) {
dataVariable.set(userName);
}
public String readDataFromThreadLocal () {
if (dataVariable.get() != null) {
return (String) dataVariable.get();
}
}
public static ServiceVersionHolder getInstance () {
if (dataHolderVar == null) {
dataHolderVar = new YourDataHolder();
}
return dataHolderVar;
}
}
Use synchronized for multithreading.
public static synchronized final Singleton getInstance() {
This way the threads will "lock" the method: only one thread will be allowed to enter the method at a time, other threads will block until the method is unlocked (the thread executing it leaves). You won't have those concurrency issues.
Also you don't need 2 singletons (which IMHO actually makes no sense and defeats the very own purpose of a singleton...).

Categories