While Implementing Singleton the following things should be answered

  1. Reflection
  2. Serialization
  3. Cloning

Objects for Singleton Classes implemented using private Constructor can be invoked by Reflection as below

Item3.java

package com.mugil.org.ej;

import java.lang.reflect.Constructor;

public class Item3 {
	public static void main(String[] args) 
	{
		// reflection concept to get constructor of a Singleton class.  
		Constructor<Singleton> constructor;
		
		try {			
			constructor = Singleton.class.getDeclaredConstructor();
			
			// change the accessibility of constructor for outside a class object creation.
			constructor.setAccessible(true);
			
			// creates object of a class as constructor is accessible now.
			Singleton secondOb = constructor.newInstance();
			System.out.println(secondOb.getName());
			
			// close the accessibility of a constructor.
			constructor.setAccessible(false);
		} catch (Exception e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}


class Singleton {

    private static Singleton instance = new Singleton();

    /* private constructor */
    private Singleton() {}

    public static Singleton getDefaultInstance() {
        return instance;
    }
    
    public String getName()
    {
    	return "MyName";
    }
}

Output

MyName

Singleton and Serialization
Without readResolve() Method

// Java code to explain effect of 
// Serilization on singleton classes
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
class Singleton implements Serializable 
{
    // 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) 
    {
        try
        {
            Singleton instance1 = Singleton.instance;
            ObjectOutput out
                = new ObjectOutputStream(new FileOutputStream("file.text"));
            out.writeObject(instance1);
            out.close();
     
            // deserailize from file to object
            ObjectInput in 
                = new ObjectInputStream(new FileInputStream("file.text"));
             
            Singleton instance2 = (Singleton) in.readObject();
            in.close();
     
            System.out.println("instance1 hashCode:- "
                                                 + instance1.hashCode());
            System.out.println("instance2 hashCode:- "
                                                 + instance2.hashCode());
        } 
         
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
}

Output

instance1 hashCode:- 1550089733
instance2 hashCode:- 785945

With readResolve() Method

// Java code to remove the effect of 
// Serialization on singleton classes
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
class Singleton implements Serializable 
{
    // public instance initialized when loading the class
    public static Singleton instance = new Singleton();
     
    private Singleton() 
    {
        // private constructor
    }
     
    // implement readResolve method
    protected Object readResolve()
    {
        return instance;
    }
}
 
public class GFG 
{
 
    public static void main(String[] args) 
    {
        try
        {
            Singleton instance1 = Singleton.instance;
            ObjectOutput out 
                = new ObjectOutputStream(new FileOutputStream("file.text"));
            out.writeObject(instance1);
            out.close();
         
            // deserailize from file to object
            ObjectInput in 
                = new ObjectInputStream(new FileInputStream("file.text"));
            Singleton instance2 = (Singleton) in.readObject();
            in.close();
         
            System.out.println("instance1 hashCode:- "
                                           + instance1.hashCode());
            System.out.println("instance2 hashCode:- "
                                           + instance2.hashCode());
        } 
         
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Output

instance1 hashCode:- 1550089733
instance2 hashCode:- 1550089733

Refer https://codethataint.com/blog/singleton-and-serialization/

// JAVA code to explain cloning 
// issue with singleton
class SuperClass implements Cloneable
{
  int i = 10;
 
  @Override
  protected Object clone() throws CloneNotSupportedException 
  {
    return super.clone();
  }
}
 
// Singleton class
class Singleton extends SuperClass
{
  // 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) throws CloneNotSupportedException 
  {
    Singleton instance1 = Singleton.instance;
    Singleton instance2 = (Singleton) instance1.clone();
    System.out.println("instance1 hashCode:- "
                           + instance1.hashCode());
    System.out.println("instance2 hashCode:- "
                           + instance2.hashCode()); 
  }
}

Output

Output :- 
instance1 hashCode:- 366712642
instance2 hashCode:- 1829164700

Two different hashCode means there are 2 different objects of singleton class.

To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton.

// JAVA code to explain overcome 
// cloning issue with singleton
class SuperClass implements Cloneable
{
  int i = 10;
 
  @Override
  protected Object clone() throws CloneNotSupportedException 
  {
    return super.clone();
  }
}
 
// Singleton class
class Singleton extends SuperClass
{
  // public instance initialized when loading the class
  public static Singleton instance = new Singleton();
 
  private Singleton() 
  {
    // private constructor
  }
 
  @Override
  protected Object clone() throws CloneNotSupportedException 
  {
    throw new CloneNotSupportedException();
  }
}
 
public class GFG
{
  public static void main(String[] args) throws CloneNotSupportedException 
  {
    Singleton instance1 = Singleton.instance;
    Singleton instance2 = (Singleton) instance1.clone();
    System.out.println("instance1 hashCode:- "
                         + instance1.hashCode());
    System.out.println("instance2 hashCode:- "
                         + instance2.hashCode()); 
  }
}

Output

Output:-
Exception in thread "main" java.lang.CloneNotSupportedException
	at GFG.Singleton.clone(GFG.java:29)
	at GFG.GFG.main(GFG.java:38)

If you don;t want to throw exception you can also return the same instance from clone method.

// JAVA code to explain overcome 
// cloning issue with singleton
class SuperClass implements Cloneable
{
  int i = 10;
 
  @Override
  protected Object clone() throws CloneNotSupportedException 
  {
    return super.clone();
  }
}
 
// Singleton class
class Singleton extends SuperClass
{
  // public instance initialized when loading the class
  public static Singleton instance = new Singleton();
 
  private Singleton() 
  {
    // private constructor
  }
 
  @Override
  protected Object clone() throws CloneNotSupportedException 
  {
    return instance;
  }
}
 
public class GFG
{
  public static void main(String[] args) throws CloneNotSupportedException 
  {
    Singleton instance1 = Singleton.instance;
    Singleton instance2 = (Singleton) instance1.clone();
    System.out.println("instance1 hashCode:- "
                           + instance1.hashCode());
    System.out.println("instance2 hashCode:- "
                           + instance2.hashCode()); 
  }
}

Output

Output:-
instance1 hashCode:- 366712642
instance2 hashCode:- 366712642

The Best way to implement Singleton is by using ENUM which takes care of Serialization and Other Issues on its own.

Singleton.java

public class Singleton 
{ 
    private static Singleton instance;   
 
    private Singleton() {}

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

In a Multi-threaded Environment

  1. Two Threads, Thread A and Thread B tries to access Object of Singleton class
  2. Thread A and B does call to Static getInstance() method
  3. Now when Thread A tries to do Null Check of instance instance == null chances of Thread B also entered the if block exists
    .
    .
    .
    if (instance == null) 
    {
      //Two threads may have passed the condition and might have got in
      instance = new Singleton();
    }
    .
    .
    .
    
  4. Now both the Threads have their own instance for the Singleton class.
  5. So there would be 2 instances of Singleton class at the end of if Block

Now there are many work arounds but DoubleCheckedLocking, Enum Singleton and Initialization On Demand Holder are the Optimized approach

Refer Table in Link

Method 1
In this method we does static block initialization of Singleton along with synchronized getInstance() method which allows the access to only one thread at a point of time.
Singleton.java

public class Singleton 
{
    private static Singleton instance;
 
    private Singleton() {}

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

But the above method is expensive since there is unnecessary locking and unlocking done every time the object get accessed.

Method 2(Double Checked Locking Singleton)
Instead of synchronizing the whole method lets synchronize the block of code which allows single thread to access the instance during the first time access.The consecutive thread would be served with the same thread allocated for the First thread once it is done with its task.

Singleton.java

public class Singleton 
{
    private volatile static Singleton instance;

    private Singleton() {}

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

Other ways of achieving singleton are by using Eager Initialization and ENUM which has its own advantages and disadvantages.

In which scenario we should serialize a singleton?
Imagine you have a long-running app and want to be able to shut it down and later continue at the point where it was shut down (e.g. in order to do hardware maintenance). If the app uses a singleton that is stateful, you’d have to be able to save and restore the sigleton’s state, which is most easily done by serializing it.

Is it possible to serialize a singleton object?
2 Methods

  1. By using ENUM : ENUM implements Serializable by Default
  2. By adding implements Serializable to class to make it serializable, and delaring all instance fields transient (to prevent a serialization attack) and provide a readResolve method.

readResolve() method in Singleton Class implementing Serialization

.
.
// readResolve method to preserve singleton property
private Object readResolve() {
     // Return the one true Elvis and let the garbage collector
     // take care of the Elvis impersonator.
    return INSTANCE;
}
.
.

Why you need readResolve() Method
This method will be invoked when you will de-serialize the object. Inside this method, you must return the existing instance to ensure single instance application wide.

The Way serialization works is as below

Serializes the Object Property -> Stores to Persistent Storage
From Persistent Storage -> Creates new Object and Sets Properties of Object

The Object Before Serialization and after Serialization are not same. Only the Object Properties are same

Now lets take a simple Example where we serializes the PrintReport Class which has priority as one of its Object Variable.priority tells which should be given first preference while printing

PrintReport.java

package com.mugil.org;

import java.io.Serializable;

public class PrintReport implements Serializable {
    private static PrintReport instance = null;
	 
    public static PrintReport getInstance() {
        if (instance == null) {
            instance = new PrintReport();
        }
        return instance;
    }
    
    private transient int priority = 2;

	public int getPriority() {
		return priority;
	}
	
	public void setPriority(int priority) {
		this.priority = priority;
	}
}

Now when the above singleton which implements serialization gets called as below

PrintMedicalReport.java

package com.mugil.org;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class PrintMedicalReport 
{	
	 static PrintReport instanceOne = PrintReport.getInstance();
	 
	    public static void main(String[] args) {
	        try {
	            // Serialize to a file
	            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
	                    "filename.ser"));
	            out.writeObject(instanceOne);
	            out.close();
	            
	            instanceOne.setPriority(1);
	            
	            // Serialize to a file
	            ObjectInput in = new ObjectInputStream(new FileInputStream(
	                    "filename.ser"));
	            PrintReport instanceTwo = (PrintReport) in.readObject();
	            in.close();
	 
	            System.out.println(instanceOne.getPriority());
	            System.out.println(instanceTwo.getPriority());
	 
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (ClassNotFoundException e) {
	            e.printStackTrace();
	        }
	    }
}

Output

1
2

Note in the above code the instanceOne.setPriority(2); should have been called before out.writeObject(instanceOne).But that is not the case since the example explains the Object are different before and after Serialization.Only Object Properties(Metadata) are stored during serialization not the actual object.

You can see the Class Prints default Priority value in the output.

Now in context to singleton we want to maintain exactly one Object exist before and after serialization. Not with two object with same set of attributes.To achieve this we add readResolve() Method.

PrintReport.java

package com.mugil.org;

import java.io.Serializable;

public class PrintReport implements Serializable {
	private volatile static PrintReport instance = null;
	 
    public static PrintReport getInstance() {
        if (instance == null) {
            instance = new PrintReport();
        }
        return instance;
    }
    
    private int priority = 1;

	public int getPriority() {
		return priority;
	}
	
	public void setPriority(int priority) {
		this.priority = priority;
	}    
	     
    protected Object readResolve() {
        return instance;
    }   
}

Now when the PrintMedicalReport class gets executed the Output would be as below

Output

1
1

When you Serialize and Deserialize new file would be created and stored in disk every time.

In the above image by changing the filename.ser text you can change the attribute of objects serialized. This is known as Serialization attack. To overcome this you must declare all instance fields as transient.

Reference 2

Lets Consider the below Singleton code which uses Double Checked Locking

DoubleCheckLocking.java

public class DoubleCheckLocking 
{
    public static class SearchBox 
    {
        private static volatile SearchBox searchBox;

        //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;
        }
}

Lets dive deep into the code where Double Checking actually takes place

  if (searchBox == null) { // first time lock
                synchronized (SearchBox.class) {
                    if (searchBox == null) {  // second time lock
                        searchBox = new SearchBox();
                    }
                }
            }
  1. Lets say we have two threads A and B and lets assume that atleast one of them reaches line 3 and observes searchBox == null is true.
  2. Two threads can not both be at line 3 at the same time because of the synchronized block. This is the key to understanding why double-checked locking works.
  3. So, it must the case that either A or B made it through synchronized first. Without loss of generality, say that that thread is A. Then, upon seeing searchBox == null is true, it will enter the body of the statement, and set searchBox to a new instance of SearchBox. It will then eventually exit the synchronized block.
  4. Now it will be B’s turn to enter: remember, B was blocked waiting for A to exit. Now when it enters the block, it will observe searchBox. But A will have left just having set searchBox to a non-null value.

Q1.What is the difference between Singleton vs Factory pattern?
A singleton pattern ensures that you always get back the same instance of whatever type you are retrieving, whereas the factory pattern generally gives you a different instance of each type.

The purpose of the singleton is where you want all calls to go through the same instance. An example of this might be a class that manages a disk cache, or gets data from a static dictionary; wherever it is important only one known instance interacts with the resource. This does make it less scalable.The purpose of the factory is to create and return new instances. Often, these won’t actually be the same type at all, but they will be implementations of the same base class. However, there may be many instances of each type

Q2.How to stop create instance via Reflection in Singleton

private Singleton() {
    if (singleton != null) {
        throw new IllegalStateException("Singleton already constructed");
    }
}

Q3.What are different ways of preventing object creation in singleton?
There are 5 ways of creating Objects. The below code explains how to prevent object creation by all 5 methods. Instead of
doing all these we can create singleton by using ENUM
Singleton.java

public class Singleton implements Serializable 
{
 private static final long serialVersionUID = 3119105548371608200 L;
 private static final Singleton singleton = new Singleton();
 
 //Prevents Class creation by Constructor
 private Singleton() 
 {
     //Prevents Object creation by reflection
     if( Singleton.singleton != null ) 
     {
        throw new InstantiationError( "Creating of this object is not allowed." );
     }
 }
 
 public static Singleton getInstance() 
 {
  return singleton;
 }
 
 //Prevents Class creation during cloning
 @Override
 protected Object clone() throws CloneNotSupportedException 
 {
  throw new CloneNotSupportedException("Cloning of this class is not allowed");
 }
 
 //Prevents New Object Creation by returning same singleton object
 protected Object readResolve() 
 {
  return singleton;
 }
}

Main.java

try {
    Class<Singleton> singletonClass = (Class<Singleton>) Class.forName("test.singleton.Singleton");
    Singleton singletonReflection = singletonClass.newInstance();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

How it Works

  1. We have JSON file with Location and Name of Factory Class
  2. Using Configuration.java we read the JSON File and read the Configuration
  3. We run TasteFoodFromMenu.java by supplying the JSON file Location as Input
  4. Now by the above method the JAR’s could be built independently and by changing the JSON file we could make changes and deploy the code without restarting the Server

For more detail refer here

Configuration.java

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Configuration {

    public static Configuration loadConfiguration(String fileName) throws IOException {    	
    	//Read Name of File
        Path path = FileSystems.getDefault().getPath(fileName);
        
        //Read Contents of File
        String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        
        ObjectMapper mapper = new ObjectMapper();
        
        //Map Location and FactoryType
        Configuration config = mapper.readValue(contents, Configuration.class);
        return config;
    }

    private String factoryType;
    private String location;


    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getFactoryType() {
        return factoryType;
    }

    public void setFactoryType(String factoryType) {
        this.factoryType = factoryType;
    }
}

TasteFoodFromMenu.java

public class TasteFoodFromMenu {
	  public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
	        Configuration configuration = Configuration.loadConfiguration(args[0]);
	        String location = configuration.getLocation();
	        URL url = new URL(location);
	        URLClassLoader ucl = new URLClassLoader(new URL[]{url});
	        Class<IFoodFactory> cls = (Class<IFoodFactory>) Class.forName(configuration.getFactoryType(), true, ucl);
	        IFoodFactory cameraFactory = cls.newInstance();
	        IFood camera = cameraFactory.prepareFood(); 
	        camera.serveFood();
	    }
}

config.json

{
  "factoryType": "com.mugil.food.ChineseFoodFactory",
  "location": "file:///D:/java/ReadConfFromJSON/lib/FoodMenu.jar"
}

What is Telescoping Constructor Pattern?
In Java, there is no support for default values for constructor parameters. As a workaround, a technique called “Telescoping constructor” is often used. A class has multiple constructors, where each constructor calls a more specific constructor in the hierarchy, which has more parameters than itself, providing default values for the extra parameters.

We’ve all at some point encountered a class with a list of constructors where each addition adds a new option parameter

Pizza(int size) { ... }        
Pizza(int size, boolean cheese) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }

Disadvantage
This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

The better alternative is to use the Builder Pattern.

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

    public Pizza build() {
      return new Pizza(this);
    }
  }

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder’s setter methods return the Builder object they are able to be chained.

Pizza pizza = new Pizza.Builder(12)
                       .cheese(true)
                       .pepperoni(true)
                       .bacon(true)
                       .build();

This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

Factory Patterns vs Builder Pattern
Consider a restaurant. The creation of “today’s meal” is a factory pattern, because you tell the kitchen “get me today’s meal” and the kitchen (factory) decides what object to generate, based on hidden criteria.

The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) “I need a pizza; add cheese, onions and bacon to it!” Thus, the builder exposes the attributes the generated object should have, but hides how to set them.

The Servlet which loads the Singleton class should be loaded during the server startup

ConfigServlet.java

public class ConfigServlet extends HttpServlet
{	
	@Override
	public void init() throws ServletException
	{
	  super.init();
	  SingletonDBConnection.getInstance();
	}
}

web.xml

<servlet>
   <servlet-name>StartUpServlet</servlet-name>
   <servlet-class>com.mugil.tutor.ConfigServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

DBConnection.java

public class DBConnection
{
	public Connection getDBConnection()
	{
		Connection connection = null;

		try
		{
			connection = DriverManager.getConnection(
					"HOST_NAME", "USER_NAME", "PASSWORD");

		}
		catch (SQLException e)
		{
			e.getLocalizedMessage();	
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			return null;
		}
		return connection;
	}
}

SingletonDBConnection.java

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class SingletonDBConnection
{
	private static SingletonDBConnection singleInstance;
	private static DataSource dataSource;
	private static Connection dbConnect;
	
	private SingletonDBConnection()
	{
		try
		{
			Context initContext = new InitialContext();
			Context envContext  = (Context) initContext.lookup("java:/comp/env");
			dataSource		   = (DataSource) envContext.lookup("jdbc/testdb");
			
			try
			{
				dbConnect  = dataSource.getConnection();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			} 	
		}
		catch (NamingException e)
		{
			e.printStackTrace();
		}
	}
	
	public static SingletonDBConnection getInstance()
	{
		if(singleInstance == null)
		{
			synchronized (SingletonDBConnection.class)
			{
				if(singleInstance == null)
				{
					singleInstance = new SingletonDBConnection();
				}
			}
		}

		return singleInstance;
	}
	
	public static Connection getConnInst()
	{
		try
		{
			dbConnect = dataSource.getConnection();
		}
		catch (SQLException e1)
		{
			e1.printStackTrace();
		}
		
		if(dbConnect == null)
		{
			try
			{
				Context initContext = new InitialContext();
				Context envContext  = (Context) initContext.lookup("java:/comp/env");
				dataSource		    = (DataSource) envContext.lookup("jdbc/testdb");
				
				try
				{
					dbConnect  = dataSource.getConnection();
				}
				catch (SQLException e)
				{
					e.printStackTrace();
				} 	
			}
			catch (NamingException e)
			{
				e.printStackTrace();
			}
		}
		
		return dbConnect;		 
	}
}

ListUsers.java

public List<User> getUsersList()
	{
		Connection conn;
		Statement  stmt = null;
		ResultSet  rs;
		List<User> arrUsersList = new ArrayList<User>();
		conn = SingletonDBConnection.getInstance().getConnInst();
		
		String strSQL = "SELECT UserId, UserName, Gender, UserLocation " +
						"  FROM tblusers";
		
		try
		{
			stmt = conn.createStatement();			
			rs = stmt.executeQuery(strSQL);
			
			while(rs.next())
			{
				User objUser = new User();
				objUser.setUserId(rs.getString("UserId"));
				objUser.setUserName(rs.getString("UserName"));
				objUser.setUserGender(rs.getString("Gender"));
				objUser.setUserLocation(rs.getString("UserLocation"));
				arrUsersList.add(objUser);
			}
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
		}
		
		
		return arrUsersList;
	}