DEV Community

Cover image for Singleton Scope in Spring: One Bean to Rule Them All! šŸ†
Akshay Gengaje
Akshay Gengaje

Posted on

Singleton Scope in Spring: One Bean to Rule Them All! šŸ†

Singleton Scope in Spring: One Bean to Rule Them All! šŸ†

Ah, Singleton Scopeā€”the default, the OG, the one who wears the crown in the world of Spring. If youā€™ve ever wondered how Spring manages bean creation and why everyone keeps talking about this ā€œSingletonā€ thing, youā€™re in for a treat! šŸ¬

In this blog, weā€™ll explore what Singleton Scope is, how it works in Spring, and why itā€™s the default choice for most use cases. Ready to dive into the world of ā€œone bean to rule them allā€? Letā€™s go! šŸš€


What is Singleton Scope? šŸ¤”

In Spring, Singleton means that only one instance of a bean is created per Spring IoC container. Itā€™s like having a master key that opens all the doors. Every time you request a bean of that type, Spring gives you the exact same instance, instead of creating a new one.

Picture this: you have a coffee shop ā˜•ļø, and every time someone orders a latte, you serve the same cup to everyone (donā€™t worry, in Springā€™s world, this makes sense!). Thatā€™s Singleton Scopeā€”one cup of latte, many sips. šŸ˜„

Key points about Singleton Scope:

  1. One bean instance per Spring IoC containerā€”no matter how many times you request it.
  2. Itā€™s thread-safe, meaning the same instance is shared across multiple requests.
  3. Itā€™s the default scope in Spring, so if you donā€™t specify a scope, youā€™re using Singleton!

Why Singleton? šŸ¤·ā€ā™‚ļø

Imagine youā€™re building a Spring app that manages user profiles. If youā€™re loading the same user profile repeatedly, it would be super inefficient to create a new bean each time you need it. This is where Singleton Scope shinesā€”Spring gives you one instance and serves it every time you ask for it, saving memory and speeding things up. šŸƒā€ā™‚ļøšŸ’Ø

The Big Benefits of Singleton Scope:

  • Memory Efficiency: Why create a new instance every time when you can reuse the one you already have? šŸ§ 
  • Faster Performance: No time wasted on repeatedly initializing beansā€”just grab the Singleton instance and go! šŸš—šŸ’Ø
  • Consistency: Since youā€™re always dealing with the same instance, thereā€™s less room for unexpected behavior or data inconsistency.

How Does Singleton Work in Spring? šŸ”„

Letā€™s break it down. When the Application Context starts up, Spring creates a single instance of each @bean or @Component thatā€™s marked with Singleton scope (by default). This instance is stored in the IoC container, and anytime your app needs that bean, Spring serves up the same instanceā€”like a well-trained butler. šŸ›Žļø

Letā€™s see a quick example in action!


Example: Singleton Scope in Code šŸ–„ļø

Hereā€™s how Singleton Scope works under the hood with a simple code example:

@Component
public class CoffeeMaker {
    public CoffeeMaker() {
        System.out.println("Creating a new CoffeeMaker instance!");
    }

    public void brew() {
        System.out.println("Brewing coffee...");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, CoffeeMaker is a simple Spring bean marked with @Component, and because we donā€™t specify any scope, it defaults to Singleton Scope. Letā€™s see what happens when we request it multiple times:

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

CoffeeMaker coffeeMaker1 = context.getBean(CoffeeMaker.class);
CoffeeMaker coffeeMaker2 = context.getBean(CoffeeMaker.class);

coffeeMaker1.brew();
coffeeMaker2.brew();

System.out.println(coffeeMaker1 == coffeeMaker2); // true, same instance!
Enter fullscreen mode Exit fullscreen mode

Output:

Creating a new CoffeeMaker instance!
Brewing coffee...
Brewing coffee...
true
Enter fullscreen mode Exit fullscreen mode

Here, Spring only created one instance of CoffeeMaker, even though we requested it twice. The output confirms that coffeeMaker1 and coffeeMaker2 are the same instance. Singleton magic! āœØ


What Happens Under the Hood? šŸ”§

When Spring initializes the Application Context, it:

  1. Creates the Singleton beans and stores them in a map-like structure (think of it as a bean registry).

  2. Every time you ask for a bean (context.getBean()), Spring checks this map to see if the bean already exists.

  3. If it exists, it serves up the same instance. If it doesnā€™t, it creates it once and then reuses it forever (well, until the Application Context is closed).

This way, you always get the same instance whenever you request a Singleton bean!


Race Conditions and Thread Safety āš ļø

While Singleton Scope is efficient, itā€™s not without its risksā€”especially when it comes to race conditions in a multi-threaded environment. Because a Singleton bean is shared across all requests, if multiple threads are trying to update the state of that bean at the same time, it could lead to unpredictable behavior and bugs. šŸ›

Imagine two coffee drinkers trying to brew coffee in the same machine at onceā€”it could result in a mess! ā˜•ļøšŸ¤Æ

To learn more about how race conditions occur and how to avoid them, check out our Race Condition Blog. Itā€™s essential to manage concurrency in Singleton beans to ensure they remain thread-safe!


When Should You Use Singleton Scope? šŸ¤”

Singleton Scope is great for:

  • Stateless Beans: If your bean doesnā€™t hold any state (like session data), Singleton is the way to go. Examples include utility classes, service layers, or DAOs (Data Access Objects).

  • Configuration or Constant Values: If your bean is holding configuration data or constants, Singleton ensures that the same values are shared across the app.

Singleton is not recommended for beans that hold user-specific data or session-scoped objectsā€”for those, youā€™ll want to use other scopes like prototype or request (weā€™ll save that for another blog šŸ˜‰).


The Limitations of Singleton Scope šŸ›‘

While Singleton is great, itā€™s not the one-size-fits-all solution for everything.

  • Statefulness: If your bean holds state, like user data or session-specific info, Singleton might lead to weird bugs (you donā€™t want to share user info between requests šŸ˜…).

  • Not Ideal for Web Apps: In a web app with multiple concurrent users, having a single bean instance could cause race conditions or thread-safety issues, depending on how itā€™s used. Youā€™ll need to handle such cases carefully to prevent concurrency issues.

For these cases, you should use other scopes like Prototype, Request, or Sessionā€”but for most general-purpose beans, Singleton is the MVP. šŸ†


Conclusion: Singleton Is Springā€™s Go-To Guy šŸ’¼

The Singleton Scope in Spring is like the VIP treatmentā€”one bean, many uses, great efficiency. Itā€™s the default scope for a reason, providing memory efficiency, performance boosts, and consistency across your app. By using Singleton, Spring ensures that your beans are always available and ready to use, without wasting precious resources.

But remember: Singleton is best for stateless or reusable beans. For anything user-specific or state-heavy, consider using other scopes to avoid unwanted bugs.

So next time youā€™re sipping that coffee ā˜•ļø (brewed by your trusty Singleton CoffeeMaker bean), remember that itā€™s all thanks to the magic of Singleton Scope!

Top comments (0)