Open In App

Singleton Class in Android

Improve
Improve
Like Article
Like
Save
Share
Report

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

Java




public class singleTonExample {
    // private static instance variable to hold the singleton instance
    private static volatile singleTonExample INSTANCE = null;
  
    // private constructor to prevent instantiation of the class
    private singleTonExample() {}
  
    // public static method to retrieve the singleton instance
    public static singleTonExample getInstance() {
        // Check if the instance is already created
        if(INSTANCE == null) {
            // synchronize the block to ensure only one thread can execute at a time
            synchronized (singleTonExample.class) {
                // check again if the instance is already created
                if (INSTANCE == null) {
                    // create the singleton instance
                    INSTANCE = new singleTonExample();
                }
            }
        }
        // return the singleton instance
        return INSTANCE;
    }
}


Kotlin




class singleTonExample {
    // private volatile instance variable to hold the singleton instance
    @Volatile
    private var INSTANCE: singleTonExample? = null
  
    // public function to retrieve the singleton instance
    fun getInstance(): singleTonExample? {
        // Check if the instance is already created
        if (INSTANCE == null) {
            // synchronize the block to ensure only one thread can execute at a time
            synchronized(this) {
                // check again if the instance is already created
                if (INSTANCE == null) {
                    // create the singleton instance
                    INSTANCE = singleTonExample()
                }
            }
        }
        // return the singleton instance
        return INSTANCE
    }
}


This is an example of a singleton class in Java and Kotlin:

Which is a class that can only have one instance at any given time. The getInstance() function is used to retrieve the singleton instance and creates it if it doesn’t already exist. The function uses the synchronized block to ensure that only one thread can execute the creation of the instance at a time, preventing any race conditions that could occur if multiple threads try to create the instance simultaneously. The @Volatile annotation is used to make sure that the singleton instance is created only once and is visible to all threads.

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.

Conclusion

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.



Last Updated : 09 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads