Ref - click
Showing posts with label singleton class. Show all posts
Showing posts with label singleton class. Show all posts
Sunday, June 23, 2019
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:
- public class SingletonExe {
- private static SingletonExe instance = null;
- private void SingeltonExe() {
- System.out.println("Private constructor");
- }
- public static SingletonExe getInstance() {
- if (instance == null) {
- synchronized (SingletonExe.class) {
- if (instance == null) {
- instance = new SingletonExe();
- }
- }
- }
- return instance;
- }
- }
[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
*/
- public class SingletonExe {
- private static volatile SingletonExe instance = null; // volatile variables
- private void SingeltonExe() {
- System.out.println("Private constructor");
- }
- public static SingletonExe getInstance() {
- if (instance == null) {
- synchronized (SingletonExe.class) {
- if (instance == null) {
- instance = new SingletonExe();
- }
- }
- }
- return instance;
- }
- }
Subscribe to:
Posts (Atom)
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...
-
Problem statement: There is a colony of 8 cells arranged in a straight line where each day every cell competes with its adjacent cells(neig...
-
Problem statement: Given an array of positive or negative integer. How will you write an algorithm to find out the largest element in the ...
-
Problem statement: Write a function to print spiral order traversal of a tree. For example. Input - 10 J H I A C D F E B G...