Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Singleton Class in Android
Next article icon

Singleton Class in Android

Last Updated : 09 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.


Next Article
Singleton Class in Android

S

sarthakhanda
Improve
Article Tags :
  • Java
  • Kotlin
  • Android
Practice Tags :
  • Java

Similar Reads

    Singleton Class in Kotlin
    Singleton Class in Kotlin is also called as the Singleton Object in Kotlin. Singleton class is a class that is defined in such a way that only one instance of the class can be created and used everywhere. Many times we create the two different objects of the same class, but we have to remember that
    4 min read
    AsyncTasks in Android
    AsyncTask is an abstract class in Android that offers us the freedom to execute demanding tasks in the background while keeping the UI thread light and the application responsive. When launched, an Android application operates in a single thread. Due to this single-thread approach, tasks that take a
    4 min read
    Android Studio Main Window
    Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps, such as: A blended environment where one can
    4 min read
    OOPs Concepts in Android
    Object-oriented programming (OOP) is a programming paradigm that is based on the concept of "objects", which can contain data and code that manipulates that data. In Android, Java is the primary programming language used for developing Android apps. Java is an object-oriented language and it provide
    8 min read
    Services in Android with Example
    Services in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains active in the background so that the user can operate multiple applications at t
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences