Nuances of Java development

This blog is about Java development and describes in detail the most interesting topics

Posts with tag «dependency injection»

All you want to know about Singleton

The singleton design pattern is one of the most inappropriately used patterns. In this article we review several implementations of a singleton that work correctly in multithreaded environment, with serialization and cloning tasks and even with reflection attacks.

Contents ✓What for you can use singleton ✓Distinction from static class ✓Lazy or eager loading singleton? ✓Eager loading singleton ✓Rough synchronization ✓Double-checked locking singleton ✓Initialization-on-demand holder idiom ✓The enum based singleton ✓Problems with serialization and deserialization ✓Problems with clone ✓Problems with reflection ✓So, why you can think about singleton as anti-pattern? ✓Conclusion What for you can use singleton The singleton pattern is used when there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point or when the single instance should be extensible by sub-classes, and clients should be able to use an extended instance without modifying their code. Distinction from static class JDK has examples of both singleton and static, on the one hand java.lang.Math is a final class with static methods, on the other hand java.lang.Runtime is a singleton class. Advantages of singleton ✓If your need to maintain state than singleton pattern is better choice than static class, because maintaining state in static class leads to bugs, especially in concurrent environment, that could lead to race conditions without adequate synchronization parallel modification by multiple threads. ✓Singleton class can be lazy loaded if its a heavy object, but static class doesn't have such advantages and always eagerly loaded. ✓With singleton, you can use inheritance and polymorphism to extend a base class, implement an interface and provide different implementations. ✓Since static methods in Java cannot be overridden, they lead to inflexibility. On the other hand, you can over... Read more

November 2019

Subscribe to blog

Search on site