Singleton Class in Android
The Singleton Pattern is a software design pattern that restricts the instantiation of a class to just “one” instance. It is used in Android Applications when an item needs to be created just once and used across the board. The main reason for this is that repeatedly creating these objects, uses up system resources. The identical object should therefore only be created once and used repeatedly. It is utilized in situations where we only require a single instance of the class, such as with network services, databases, etc. We, therefore, create a singleton class to implement the Singleton pattern in our project or product. In this article, we’ll look at how to create singleton classes in Java and Kotlin.
Advantages of the Singleton Pattern
Many objects in a normal Android app only require a single global instance, whether they are used directly or are simply passed to another class. Examples include caches, the repository class, Retrofit, Gson, OkHttpClient, HttpLoggingInterceptor, and SharedPreferences. If we were to instantiate more than one of these kinds of objects, we would encounter issues like inaccurate app behavior, resource usage, and other unexpected outcomes.
Properties of Singleton Class
The characteristics of a typical singleton class are listed below:
- Only one instance: The singleton class only has one instance, which is accomplished by offering a class instance inside another class. Additionally, it should be made impossible for outside classes and subclasses to create the instance.
- Globally accessible: Each class should be able to use the singleton class instance as it should be globally accessible.
Rules for Making a Class Singleton
To create a Singleton class, the guidelines listed below must be adhered to:
- A private constructor
- A static reference of its class
- One static method
- Globally accessible object reference
- Consistency across multiple threads
Singleton Example with Multi Thread Lazy Initialisation
The volatile keyword makes this singleton instance thread safe with a private constructor, and we are performing two checks of “is equal to null” in the getInstance method. For instance, if we have two threads A and B, only one of them will be able to enter the synchronized block and both of them will observe that the instance is null at the synchronized keyword. Now, A enters while B waits, and when A notices the instance is null, A will create a new instance and leave the block. When thread B enters, it will notice that the instance is not null and then have the instance created by threat A itself.
You learned about the Singleton pattern in Android in this brief tutorial, including what it is, why it’s useful, how to use it in your own code, and a few strategies for handling many threads.