Friday, April 27, 2018

Singleton class or singleton pattern in java ?

  • Singleton is a class which has only one instance in whole application and provide getInstance() method to access singleton instance. 
  • There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.
Example:
[1] Singleton by private static field, static getInstance() method:
  1. public class SingletonExe {
  2. private static SingletonExe instance = null;
  3. private void SingeltonExe() {
  4. System.out.println("Private constructor");
  5. }
  6. public static SingletonExe getInstance() {
  7.   if (instance == null) {
  8.   synchronized (SingletonExe.class) {
  9. if (instance == null) {
  10. instance = new SingletonExe();
  11. }
  12.   }
  13.   }
  14. return instance;
  15. }
  16. }

[2] Singleton by synchronized getInstance() method [double checked locking in Singleton]

/**
 * Java program to demonstrate where to use Volatile keyword in Java. In this
 * example Singleton Instance is declared as volatile variable to ensure every
 * thread
 */
  1. public class SingletonExe {
  2. private static volatile SingletonExe instance = null; // volatile variables
  3. private void SingeltonExe() {
  4. System.out.println("Private constructor");
  5. }
  6. public static SingletonExe getInstance() {
  7. if (instance == null) {
  8. synchronized (SingletonExe.class) {
  9. if (instance == null) {
  10. instance = new SingletonExe();
  11. }
  12. }
  13. }
  14. return instance;
  15. }
  16. }

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...