Singleton java
Examples of DIFFERENT Singleton Design Pattern¶
Eager Initialization¶
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Pros¶
- Useful if Singleton utilizes minimal resources.
Cons¶
- Object is created even if client doesn’t use it.
- No ability to handle exceptions.
- Reflection can destroy this Singleton implementation.
Static Block Initialization¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Pros¶
- Useful if Singleton utilizes minimal resources.
- Allows for exception handling.
Cons¶
- Object is created even if client doesn’t use it.
- Reflection can destroy this Singleton implementation.
Lazy Initialization¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Pros¶
- Initialized only when needed.
- Allows for exception handling.
Cons¶
- Not Thread-safe (i.e. would fail in multi-threaded code).
- Reflection can destroy this Singleton implementation.
Thread-Safe Lazy Singleton¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Pros¶
- Initialized only when needed.
- Allows for exception handling.
- Thread-Safe
Cons¶
- Reduced performance in synchronization.
- Fails in Java 5 in certain scenarios where too many threads tried to get the instance of the singleton class simultaneously due to OLD Java memory model.
- Reflection can destroy this Singleton implementation.
Thread-Safe Lazy Double-Checked Locking Singleton¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Pros¶
- Initialized only when needed.
- Allows for exception handling.
- Thread-Safe
Cons¶
- Fails in Java 5 in certain scenarios where too many threads tried to get the instance of the singleton class simultaneously due to OLD Java memory model.
- Reflection can destroy this Singleton implementation.
Bill Pugh Singleton Implementation¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Pros¶
- Initialized only when needed.
- Allows for exception handling.
- Thread-Safe
- Works well even in Java 5
Cons¶
- Reflection can destroy this Singleton implementation.
Enum Singleton¶
1 2 3 4 5 6 7 8 9 10 |
|
Pros¶
- Enum guarantees single instantiation and global access.
- Thread-Safe
- Reflection CANNOT destroy this Singleton implementation.
Cons¶
- Created even if client doesn’t use it.
How Reflection Destroys Most Singleton Implementations!¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Issues with Serialization¶
- Serialization is when we need to store an object to the file-system, or other storage media, for later retrieval.
- The de-serialization of the stored object creates a new instance, however. This defeats the idea of a Singleton.
Example of Defeating Singleton with De-serialization¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
How to fix Serialization Issue¶
- Add an override of readResolve method to your Singleton
1 2 3 |
|