-
Notifications
You must be signed in to change notification settings - Fork 1
Singleton
Singleton: wiki
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance.
Singleton UML Class diagram:
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
An implementation of the singleton pattern must:
-
The singleton class must provide a global access point to get the instance of the class.
private static Singleton instance = null;
-
Hide the constructor of the class. Declaring all constructors of the class to be private[ACCESS-MODIFIER]
private Singleton() { if (instance != null) { // To avoid ReflectionAPI access. throw new ReflectionException("Cannot create, please use getInstance()"); } }
Reflection can be caused to destroy singleton property of singleton class. To overcome creating of instance form private constructor throw Exception.
-
Define a public static operation (getInstance()) that returns the sole instance of the class. And ensure that only one instance of the singleton class ever exists; and
public static synchronized Singleton getInstance() { // SafeLazyInitialization, ThreadSafe if (instance == null) { instance = new Singleton(); } return instance; }
Double-checked locking should not be used (squid:S2168)
Reflection API: throw exception form the constructors.
public static Singleton reflectionAPI() throws Exception {
Singleton instance = null;
Constructor[] constructors = Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
instance = (Singleton) constructor.newInstance();
break;
}
return instance;
}class ReflectionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ReflectionException(String message) {
super(message);
}
}Cloning: Cloning is a concept to create duplicate objects. Using clone we can create copy of object. Suppose, we create clone of a singleton object, then it will create a copy that is there are two instances of a singleton class, hence the class is no more singleton.
"clone" should not be overridden (squid:S2975)
@Override
protected Object clone() throws CloneNotSupportedException {
//return super.clone();
//throw new CloneNotSupportedException();
return instance;
}Overcome Cloning issue:- 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.
Now we have stopped user to create clone of singleton class by throwing the exception, or If you don;t want to throw exception you can also return the same instance from clone method.
Serialization:- Serialization can also cause breakage of singleton property of singleton classes. Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.
To Overcome serialization issue:- We have to implement method readResolve() method. "readResolve" methods should be inheritable (squid:S2062), Visibility[ACCESS-MODIFIER] should not be private.
private static final long serialVersionUID = 42L;
protected Object readResolve() throws ObjectStreamException {
return getInstance();
}
public static void writeStream(String fileName, Object instance) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
oos.writeObject(instance);
oos.close();
}
public static Singleton readStream(String fileName) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
Singleton readObject = (Singleton) ois.readObject();
ois.close();
return readObject;
}Enum: Enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons.
enum EnumSingleton {
INSTANCE;
public void doSomething(){
System.out.println("Instance funciton.");
}
}Example:
public static void main(String[] args) throws Exception {
System.out.println("SafeLazyInitialization, ThreadSafe");
print("Initial Check", getInstance());
print("Cross Check", getInstance());
System.out.println("Serialization");
String fileName = "D:/objectSingleton.ser";
writeStream(fileName, getInstance());
print("Initial Check", readStream(fileName));
print("Cross Check", readStream(fileName));
System.out.println("Cloning is a concept to create duplicate objects.");
Singleton clone = (Singleton) getInstance().clone();
print("Copy Singleton", clone);
System.out.println("Enum singleton - the preferred approach");
EnumSingleton.INSTANCE.doSomething();
System.out.println("Reflection API");
print("Break Singleton", reflectionAPI());
}
public static void print(String message, Singleton obj) {
System.out.format("[M]:%14s, [H]:%d\n", message, System.identityHashCode(obj));
}Output:
SafeLazyInitialization, ThreadSafe | SafeLazyInitialization, ThreadSafe
[M]: Initial Check, [H]:366712642 | [M]: Initial Check, [H]:366712642
[M]: Cross Check, [H]:366712642 | [M]: Cross Check, [H]:366712642
Serialization | Serialization
[M]: Initial Check, [H]:1096979270 | [M]: Initial Check, [H]:366712642
[M]: Cross Check, [H]:1078694789 | [M]: Cross Check, [H]:366712642
Cloning of objects. | Cloning of objects.
[M]:Copy Singleton, [H]:1096979270 | [M]:Copy Singleton, [H]:366712642
Reflection API | Reflection API
[M]:Break Singleton, [H]:1096979270 | Exception in thread "main" java.lang.reflect.InvocationTargetException
| Caused by: ReflectionException: Cannot create, please use getInstance()
In JDK there are many places where Singleton design pattern is used. Some of these are as follows:
- java.lang.Runtime.getRuntime() Source
public class Runtime {
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
}- java.awt.Desktop.getDesktop() Source
- When is a Singleton not a Singleton?
Singleton pattern is used for logging, drivers objects, caching and thread pool.
In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. Basic, Refactoring Techniques
Method signature: It consists of method name and parameter list (number/type/order of the parameters). methodName(parametersList y). An instance method in a subclass with the same signature and return type as an instance method in the super-class overrides the super-class's method.
Java OOP concepts
Class - Collection of a common features of a group of object [static/instance Fields, blocks and Methods]
Object - Instance of a class (instance fields)
Abstraction - Process of hiding complex info and providing required info like API, Marker Interfaces ...
Encapsulation(Security) - Class Binding up with data members(fields) and member functions.
Inheritance (Reusability by placing common code in single class)
1. Multilevel - {A -> B -> C} 2. Multiple - Diamond problem {A <- (B) -> C} [Java not supports] 3. Cyclic {A <-> B} [Java not supports]
* Is-A Relation - Class A extends B
* Hash-A Relation - Class A { B obj = new B(); } - (Composition/Aggregation)
Polymorphism (Flexibility) 1. Compile-Time Overloading 2. Runtime Overriding [Greek - "many forms"]
int[] arr = {1,2,3}; int arrLength = arr.length; // Fixed length of sequential blocks to hold same data type
String str = "Yash"; int strLength = str.length(); // Immutable Object value can't be changed.
List<?> collections = new ArrayList<String>(); int collectionGroupSize = collections.size();
Map<?, ?> mapEntry = new HashMap<String, String>();
Set<?> keySet = mapEntry.keySet(); // Set of Key's
Set<?> entrySet = mapEntry.entrySet(); // Set of Entries [Key, Value]
// Immutable Objects once created they can't be modified. final class Integer/String/Employee
Integer val = Integer.valueOf("100"); String str2 = String.valueOf(100); // Immutable classes
final class Employee { // All Wrapper classes, java.util.UUID, java.io.File ...
private final String empName; // Field as Final(values can be assigned only once) Only getter functions.
public Employee(String name) { this.empName = name; }
} Native Java Code for Hashtable.h, Hashtable.cpp
SQL API.
You can check your current JDK and JRE versions on your command prompt respectively,
- JDK
javac -version [C:\Program Files\Java\jdk1.8.0_121\bin]o/p:javac 1.8.0_121 - JRE
java -version[C:\Program Files\Java\jdk1.8.0_121\bin]o/P:java version "1.8.0_102"
JAVA_HOME - Must be set to JDK otherwise maven projects leads to compilation error. [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? C:\Softwares\OpenJDK\, 7-zip
Fatal error compiling: invalid target release: JRE and JDK must be of same version
1.8.0.XXX
Disable TLS 1.0 and 1.1
security-libs/javax.net.ssl: TLS 1.0 and 1.1 are versions of the TLS protocol that are no longer considered secure and have been superseded by more secure and modern versions (TLS 1.2 and 1.3).
Core Java
-
Java Programming Language Basics
- Object, Class, Encapsulation, Interface, Inheritance, Polymorphism (Method Overloading, Overriding)
- JVM Architecture, Memory Areas
- JVM Class Loader SubSystem
- Core Java Interview Questions & Programs
- Interview Concepts
Stack Posts
- Comparable vs Comparator
- Collections and Arrays
-
String, StringBuffer, and StringBuilder
- String reverse
- Remove single char
- File data to String
- Unicode equality check Spacing entities
- split(String regex, int limit)
- Longest String of an array
-
Object Serialization
- Interface's Serializable vs Externalizable
- Transient Keyword
-
implements Runnablevsextends Thread - JSON
- Files,
Logging API- Append text to Existing file
- Counting number of words in a file
- Properties
- Properties with reference key