🌱 My Spring Journey : Singleton Class -> Single means one and ton means object -> A Java class that allows us to create only one object at any time is called a Singleton class. -> In Java programming, object creation is a costly process in terms of memory and CPU time. So, it is recommended to minimize object creation whenever possible. -> To make a Java class a perfect Singleton, we must take care of the following protections : a) Protection from multithreaded environment b) Protection from deserialization c) Protection from Reflection API d) Protection from cloning e) Protection from subclass loading -> In XML-driven configuration, we can use the scope attribute of the <bean> tag. -> In annotation-driven configuration, we can use the @Scope annotation to specify the scope. -> The IoC container does not make a Spring bean a perfect Singleton class just by using the "singleton" scope. Instead, it provides singleton behavior by creating only one object per bean definition. -> If we do not specify the scope explicitly, singleton becomes the default scope,and those objects are stored in the internal cache of the IoC container for reusability. Different types of scopes in Spring : -> singleton -> prototype -> request -> session -> application -> websocket -> If we configure a class as a Spring bean with singleton scope but define two different bean IDs, the IoC container will create two different objects, because it internally uses the Reflection API to create bean instances. #Java #SpringFramework #SpringCore #SingletonPattern #DesignPatterns #IOC #DependencyInjection #BackendDevelopment #JavaDeveloper
Java Singleton Class: Spring Framework and Design Patterns
More Relevant Posts
-
A weekly java concept series:- week 2 What are Sealed Classes? Introduced in Java 17, Sealed Classes let you explicitly control which classes can extend or implement them. No more unexpected subclasses! The Problem They Solve: Before: Anyone can extend Payment public abstract class Payment { abstract void process(); } Risky - unknown implementations everywhere! After: Only permitted classes can extend public sealed class Payment permits CreditCard, DebitCard, UPI { abstract void process(); } public final class CreditCard extends Payment { void process() { /* logic */ } } public final class DebitCard extends Payment { void process() { /* logic */ } } public non-sealed class UPI extends Payment { void process() { /* logic */ } } Key Benefits: ✅ Explicit control over inheritance ✅ Better domain modeling ✅ Exhaustive switch statements (no default needed!) ✅ Improved code maintainability Real-World Use Case: Perfect for modeling closed domain hierarchies like payment types, user roles, notification channels, or state machines. Exhaustive Pattern Matching: String description = switch(payment) { case CreditCard c -> "Credit payment"; case DebitCard d -> "Debit payment"; case UPI u -> "UPI payment"; }; No default needed - compiler knows all cases! Use final, sealed, or non-sealed for permitted subclasses. This creates a clear inheritance contract! #Java #JavaDevelopment #ModernJava #Java17 #SpringBoot #BackendDevelopment #SoftwareDevelopment #CleanCode #Programming #DeveloperCommunity
To view or add a comment, sign in
-
🧠 Your Java class is not loaded when the app starts, it is loaded when the JVM needs it. That single fact explains many weird runtime bugs. Let’s break down how Java loads classes at runtime 👇 📦 Step 1: Loading When the JVM encounters a class reference: 🔍 Finds the .class file (classpath, module path, or custom source) 📥 Loads bytecode into memory 🧠 Creates a Class object in Metaspace Important: ➡️ The class is not executed yet 🧪 Step 2: Linking Linking prepares the class for execution and has three parts: Verification ✔️ Ensures bytecode is valid and safe 🚫 Prevents memory corruption Preparation 📊 Allocates memory for static variables 🔢 Sets default values Resolution 🔗 Resolves symbolic references ⚙️ Converts them into direct references 🔥 Step 3: Initialization Now the class is actually initialized: ⚡ Static blocks run 🧾 Static fields get assigned real values 🏁 Class is ready for use This happens only when: • A static method or field is accessed • An object is created • The class is explicitly loaded 🧩 ClassLoader hierarchy matters Java uses multiple class loaders: 🥇 Bootstrap (core Java classes) 🥈 Platform (JDK libraries) 🥉 Application (your code) This ensures: 🔒 Security 🔁 No duplicate core classes 🧠 Predictable loading behavior ⚠️ Why this matters in real systems Most runtime issues are class-loading issues: • ClassNotFoundException • NoClassDefFoundError • Dependency conflicts • ClassLoader memory leaks Understanding class loading helps you debug these faster. 🎯 Final takeaway Java loads classes lazily, securely, and on demand. If you understand the class loading lifecycle, half of your “works locally but fails in prod” bugs disappear. #Java #JVMInternals #BackendEngineering #SystemDesign #Performance
To view or add a comment, sign in
-
-
Understanding Execution Flow and Constructors in Java Today I explored how Java executes static blocks, instance blocks, and constructors when objects are created. Key concepts I practiced: 1--> Static Block Runs only once when the class is loaded. It always prints before anything else in the class. 2--> Instance Block Executes every time an object is created, and it runs before the constructor. Useful when multiple constructors share common initialization logic. 3--> Default & Parameterized Constructors The default constructor initializes objects without arguments The parameterized constructor allows passing custom values By printing messages in each block, I clearly understood Java’s execution order: -->Static block -->Static method -->Instance block -->Constructor -->Other methods Attaching the console output below for clarity. Thanks Prasoon Bidua Sir for the guidance and support in understanding core fundamentals. #Java #Constructors #OOP #ExecutionFlow #CoreJava #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Strategy Pattern in Java The Strategy Pattern is a behavioral design pattern that lets you define a family of algorithms, encapsulate each one, and make them interchangeable. 🧩 How it works (as seen in the image): The Strategy Interface (IFileSavingStrategy): Defines the common contract for all supported algorithms. Concrete Strategies (XmlStrategy, JsonStrategy): The actual implementations of the logic. The Context: This is the class that uses the strategy. It doesn't care how the file is saved; it just knows it has a tool that can do it. 💡 Why use this? Decoupling: Your "Context" (client code) doesn't need to know the dirty details of XML or JSON parsing. Scalability: Need to support .yaml? Just create a new class. Zero changes to your existing code. Testability: You can unit test each strategy in isolation. Pro Tip: In modern Spring Boot applications, you can inject all implementations of an interface into a Map<String, FileSavingStrategy> to pick the right one at runtime dynamically! #Java #DesignPatterns #SoftwareEngineering #CleanCode #ProgrammingTips #BackendDevelopment
To view or add a comment, sign in
-
-
Variables in Java — From Code to Memory 🧠☕ In Java, a variable is more than just a name holding a value. It defines how data is stored, accessed, and managed inside the JVM. Here’s a simple breakdown 👇 🔹 Local Variables Declared inside methods or blocks Stored in Stack memory Created when a method is called, removed when it ends No default values 🔹 Instance Variables Declared inside a class (outside methods) Belong to an object Stored in Heap memory Each object has its own copy 🔹 Static Variables Declared using static Belong to the class, not objects Stored in Method Area (MetaSpace) Single shared copy across all objects How Memory Works Behind the Scenes ⚙️ 🟦 Stack Memory Stores local variables and method calls Works in LIFO order Fast and thread-safe 🟧 Heap Memory Stores objects and instance variables Shared across threads Managed by Garbage Collection 🟨 Reference Variables Stored in Stack Point to objects in Heap Why This Matters ❓ Understanding variables helps you: ✔ Write efficient code ✔ Avoid memory leaks ✔ Debug faster ✔ Perform better in interviews Strong fundamentals build strong developers 🚀 #Java #CoreJava #JVM #JavaBasics #MemoryManagement #SoftwareEngineering #Programming #LearningJourney
To view or add a comment, sign in
-
-
Behind the scenes: How Java objects are created:- What happens step by step inside the JVM: The Java source code is compiled and .class files are generated. When the program runs, Animal.class and AnimalMain.class are loaded into the Method Area (Metaspace). A java.lang.Class object is created in the Heap, which holds runtime metadata of the class. JVM creates the main thread and its stack. When, new Animal() is executed: Memory is allocated in the Heap Area. All instance variables are initialized with default values (age = 0, legs = 0). The constructor is executed. A reference to the newly created object is returned. This reference is stored in the stack variable buzo. Note:- Heap → stores objects Stack → stores references and method frames Method Area / Metaspace → stores class metadata Important: ->The reference variable does not store the actual object or a memory address. ->HashCode is generated only when hashCode() is called, not during object creation. Learning Java internals makes concepts much clearer. #Java #JVM #CoreJava #ObjectOrientedProgramming #ComputerScience #objects
To view or add a comment, sign in
-
-
Pattern Matching in Java 17: Pattern matching means checking an object’s type and safely using it as that type in a single step. In real applications, one request often represents multiple actions. Example: A request can be: • Order request • Cancel request • Refund request Each type requires different handling. Before Java 17: To handle this, Java required two separate steps: • Check the request type. • Manually cast it to use further. This worked only if the cast was always correct. During refactoring, a wrong cast could still compile and fail later at runtime. With Java 17: Java binds the cast directly to the type check. • Java checks the request type • If it matches Order, Cancel, or Refund, Java provides a correctly typed variable • If it doesn’t match, the block is skipped • A wrong cast cannot compile Same business logic. Much safer execution. Key takeaway: Pattern matching removes unsafe casting and moves errors from runtime to compile time. That’s why it matters in real-world Java projects. #Java #CoreJava #Java17 #PatternMatching #CleanCode
To view or add a comment, sign in
-
-
Pattern Matching in Java 17: Pattern matching means checking an object’s type and safely using it as that type in a single step. In real applications, one request often represents multiple actions. Example: A request can be: • Order request • Cancel request • Refund request Each type requires different handling. Before Java 17: To handle this, Java required two separate steps: • Check the request type. • Manually cast it to use further. This worked only if the cast was always correct. During refactoring, a wrong cast could still compile and fail later at runtime. With Java 17: Java binds the cast directly to the type check. • Java checks the request type • If it matches Order, Cancel, or Refund, Java provides a correctly typed variable • If it doesn’t match, the block is skipped • A wrong cast cannot compile Same business logic. Much safer execution. Key takeaway: Pattern matching removes unsafe casting and moves errors from runtime to compile time. That’s why it matters in real-world Java projects.
Pattern Matching in Java 17: Pattern matching means checking an object’s type and safely using it as that type in a single step. In real applications, one request often represents multiple actions. Example: A request can be: • Order request • Cancel request • Refund request Each type requires different handling. Before Java 17: To handle this, Java required two separate steps: • Check the request type. • Manually cast it to use further. This worked only if the cast was always correct. During refactoring, a wrong cast could still compile and fail later at runtime. With Java 17: Java binds the cast directly to the type check. • Java checks the request type • If it matches Order, Cancel, or Refund, Java provides a correctly typed variable • If it doesn’t match, the block is skipped • A wrong cast cannot compile Same business logic. Much safer execution. Key takeaway: Pattern matching removes unsafe casting and moves errors from runtime to compile time. That’s why it matters in real-world Java projects. #Java #CoreJava #Java17 #PatternMatching #CleanCode
To view or add a comment, sign in
-
-
Cleaner instanceof with Java 17 (Pattern Matching) Before Java 16/17, using instanceof meant two steps: Check the type Explicitly cast the object That led to repetitive and cluttered code. ❌ Before Java 17 if (request instanceof OrderRequest) { OrderRequest r = (OrderRequest) request; processOrder(r); } ✅ With Java 17 (Pattern Matching for instanceof) if (request instanceof OrderRequest r) { processOrder(r); } 🔥 Why this is better? ✔ No explicit casting ✔ Less boilerplate ✔ Safer (cast happens only if type matches) ✔ More readable & modern Java This small enhancement makes day-to-day backend code cleaner and less error-prone, especially when handling multiple request types. 💡 Modern Java isn’t about writing more code — it’s about writing clearer code. #Java #Java17 #CleanCode #BackendDevelopment #JavaDeveloper #Programming
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development