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)
How to run standalone mock server on local laptop
Please download the standalone wiremock server from Direct download section at the bottom of the page. Download and installation Feel fre...
-
Problem statement: what would be the better option to choose between char[] array and String. Answer: Character array i.e. char[] over ...
-
अपनी धुन में रहता हूँ मैं भी तेरे जैसा हूँ ओ पिछली रुत के साथी अब के बरस मैं तनहा हूँ अपनी धुन में... तेरी गली में सारा दिन दुख के कंकर ...
-
Please download the standalone wiremock server from Direct download section at the bottom of the page. Download and installation Feel fre...