Loop and Break

Singleton Invalidated by Multithreading

Singleton Invalidated by Multithreading

Singleton will work properly in multithreaded environment only if eager instantiation has been done because in this case instance creation will happen at the time of class loading only. But for Lazy instantiation we...

Singleton Invalidated by Serialization

Singleton Invalidated by Serialization

When we serialize an object and deserialize it again there are different hash code values generated as shown in the example below. So our Singleton principle breaks in case of object serialization/deserialization. Output How...

Singleton Invalidated by Clone

Singleton Invalidated by Clone

If we try to make instance by cloning it, the generated hash code of cloned copy doesn’t match with the actual object so it also violates the Singleton principle. Example Output How to fix:...

Singleton Invalidated by Reflection

Singleton Invalidated by Reflection

Using reflection we can set the private constructor to become accessible at runtime as shown in the example below. Example Output In above output we are seeing first two objects are assigned same hashcode,...

Singleton Design Pattern

Singleton Design Pattern

Sometimes it’s important for some classes to have exactly one instance. There are many objects we only need one instance of them and if we, instantiate more than one, we’ll run into all sorts...

Using Comparators to sort objects in Java

Using Comparators to sort objects in Java

Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. Following comparator will sort by ID Example Output You can...

Builder Design Pattern in Java

Builder Design Pattern in Java

Builder pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. There are three major issues with Factory and Abstract...

Use your class as a bean in Spring Boot

Use your class as a bean in Spring Boot

Depending on your needs, you can either leverage @ComponentScan to automatically detect your class and have an instance created, use it together with @Autowired and @Value to get dependencies or properties injected, or you...

What is the use of equals method in Java?

What is the use of equals method in Java?

Equals method is used when we compare two objects. Default implementation of equals method is defined in Object class. The implementation is similar to == operator. Two object references are equal only if they...

TreeMap in Java

TreeMap in Java

TreeMap is Red-Black tree based NavigableMap implementation. It is sorted according to the natural ordering of its keys. Example Output