𝘽𝙚𝙖𝙣 𝙎𝙘𝙤𝙥𝙚𝙨: @𝙎𝙞𝙣𝙜𝙡𝙚𝙩𝙤𝙣 𝙫𝙨. @𝙋𝙧𝙤𝙩𝙤𝙩𝙮𝙥𝙚—𝙒𝙝𝙮 𝙄𝙩 𝙈𝙖𝙩𝙩𝙚𝙧𝙨 𝙞𝙣 𝙈𝙞𝙘𝙧𝙤𝙨𝙚𝙧𝙫𝙞𝙘𝙚𝙨 𝗠𝗲𝘁𝗿𝗶𝗰: Incorrect bean scope usage is a leading cause of memory leaks in Spring microservices, often resulting in stale session data piling up and increased memory consumption. 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: Many developers default to @Singleton for all services, causing unwanted shared state across requests and users, which leads to memory leaks and performance issues. 𝗧𝗵𝗲 𝗕𝘂𝗴: // ❌ WRONG: Stateful service as singleton (default) @Service public class UserSessionService { private Map<String, SessionData> sessionMap = new HashMap<>(); // Shared across all requests and users — leads to state leakage! } 𝗧𝗵𝗲 𝗙𝗶𝘅: // ✅ CORRECT: Use @Prototype for stateful beans @Service @Scope("prototype") public class UserSessionService { private Map<String, SessionData> sessionMap = new HashMap<>(); // New instance per request prevents cross-user leakage } 𝙊𝙧 𝙚𝙫𝙚𝙣 𝙗𝙚𝙩𝙩𝙚𝙧, 𝙧𝙚𝙛𝙖𝙘𝙩𝙤𝙧 𝙩𝙤𝙬𝙖𝙧𝙙𝙨 𝙨𝙩𝙖𝙩𝙚𝙡𝙚𝙨𝙨 𝙙𝙚𝙨𝙞𝙜𝙣 𝙬𝙝𝙚𝙣𝙚𝙫𝙚𝙧 𝙥𝙤𝙨𝙨𝙞𝙗𝙡𝙚 𝙛𝙤𝙧 𝙤𝙥𝙩𝙞𝙢𝙖𝙡 𝙨𝙘𝙖𝙡𝙖𝙗𝙞𝙡𝙞𝙩𝙮. 𝗥𝗲𝗮𝗹 𝗜𝗺𝗽𝗮𝗰𝘁: After one incident, I found 15,000 stale sessions accumulating in production memory due to accidental state retention in a singleton. Switching to prototype scope and stateless beans cut memory use by up to 70%. 𝗖𝗮𝗹𝗹-𝘁𝗼-𝗔𝗰𝘁𝗶𝗼𝗻: What’s your go-to bean scope strategy in your services? Have you ever tracked down a production memory leak caused by incorrect scope? #Java #SpringBoot #Microservices #MemoryLeak #BeanScope #SoftwareEngineering #BackendDevelopment #TechTips #Programming
Ashish Tiwari’s Post
More Relevant Posts
-
Custom Validation Annotations in Spring Boot: A Practical, Reusable Pattern 🚀 Custom validation annotations in Spring Boot unlock domain rules directly in your DTOs. To implement, you define a custom annotation with @Constraint and implement ConstraintValidator to encapsulate the logic. Add spring-boot-starter-validation to enable Bean Validation. For single-field checks, annotate the field. For cross-field checks (like password confirmation), create a class-level constraint and annotate the class. A practical pattern looks like this: - Annotation interface with message, groups, payload, and @Constraint(validatedBy = ...) . - Validator class implementing ConstraintValidator<YourAnnotation, TargetType> . - Apply the annotation on the target (field or class). Best practices: - Use meaningful messages and validation groups to control context. - Keep validators focused and test them in isolation, then wire them into controllers with @Validated/@Valid. Actionable steps: - Add the validation dependency. - Define your annotation. - Implement the validator. - Apply it to your DTO. - Test with both valid and invalid payloads. ❓ What custom validations have you built, or what tricky cross-field check would you tackle next? #SpringBoot #Java #BeanValidation #HibernateValidator #Validation
To view or add a comment, sign in
-
You every thought how Spring magically detects and manages your @Service, @Repository, or @Controller classes without you explicitly declaring them. Hmmmm..... Here is how 🧩 1. Annotation Discovery Spring uses annotation-based configuration to identify which classes should become Spring-managed beans. When you enable component scanning, Spring scans the specified package (and all its sub-packages) for stereotype annotations like: @Component – generic stereotype for any Spring-managed component @Service – marks a service-layer class @Repository – marks a DAO/persistence-layer class @Controller / @RestController – marks a web controller Once detected, these classes are automatically registered in the application context. ⚙️ 2. Bean Creation and Registration When Spring discovers these annotated classes, it creates bean instances and registers them in the ApplicationContext — Spring’s central container. This registry holds all managed beans and their dependencies. From here, Spring can easily perform dependency injection, lifecycle management, and configuration. Think of the ApplicationContext as a “bean directory” where every managed component lives — and where Spring looks whenever you use @Autowired. 🧠 3. Bean Configuration and Lifecycle After registering a bean, Spring applies configuration rules: Resolving and injecting dependencies Managing lifecycle callbacks (like @PostConstruct, @PreDestroy) Handling resource management and proxy creation (for AOP or transactions) Developers can fine-tune bean behavior using: Annotations (e.g., @Qualifier, @Scope) XML configuration (legacy style) Programmatic configuration (via @Bean methods) #java #spring #springboot #javadev #springcore #springboot #javaspring
To view or add a comment, sign in
-
-
👑 𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 𝐒𝐢𝐧𝐠𝐥𝐞𝐭𝐨𝐧 𝐃𝐞𝐬𝐢𝐠𝐧 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 — 𝐎𝐧𝐞 𝐎𝐛𝐣𝐞𝐜𝐭 𝐭𝐨 𝐑𝐮𝐥𝐞 𝐓𝐡𝐞𝐦 𝐀𝐥𝐥 In the world of software design, some classes should exist only once throughout the entire application — that’s where the Singleton Design Pattern shines! It ensures that only one instance of a class is created and provides a global point of access to it. 🧩 𝐖𝐡𝐚𝐭 𝐈𝐬 𝐚 𝐒𝐢𝐧𝐠𝐥𝐞𝐭𝐨𝐧? A Singleton is a creational design pattern that restricts class instantiation to one single object. For example: A single Database Connection Manager A centralized Logger A Configuration Loader ⚙️ 𝐇𝐨𝐰 𝐈𝐭 𝐖𝐨𝐫𝐤𝐬 (𝐒𝐭𝐞𝐩-𝐛𝐲-𝐒𝐭𝐞𝐩) 1️⃣ Make the constructor private, so no one can create an instance using new. 2️⃣ Create a private static instance variable of the same class. 3️⃣ Provide a public static method (like getInstance()) that returns the same object every time. 💻 𝐂𝐨𝐝𝐞 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 (𝐓𝐡𝐫𝐞𝐚𝐝-𝐒𝐚𝐟𝐞 𝐕𝐞𝐫𝐬𝐢𝐨𝐧) public class Singleton { private static volatile Singleton instance; private Singleton() { // private constructor prevents instantiation } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } 🧠 Why volatile and synchronized? To prevent multiple threads from creating different instances during concurrent access. This is called Double-Checked Locking — efficient and thread-safe! ✨ 𝐀𝐝𝐯𝐚𝐧𝐭𝐚𝐠𝐞𝐬 ✅ Ensures only one instance of a class exists ✅ Saves memory and improves performance ✅ Centralized control for shared resources ✅ Thread-safe and globally accessible ⚠️ 𝐂𝐨𝐦𝐦𝐨𝐧 𝐌𝐢𝐬𝐭𝐚𝐤𝐞 ❌ Using Singleton in places where you actually need multiple instances (like per user/session data) can lead to unexpected bugs. 📘 𝐏𝐫𝐨 𝐓𝐢𝐩: In Spring Boot, you already get Singleton behavior by default for Beans — every @Service, @Component, or @Repository is a Singleton unless you specify otherwise. 😉 #DesignPatterns #Java #SpringBoot #SoftwareEngineering #OOP #BackendDevelopment #CleanCode #Microservices #CodingBestPractices #JavaDeveloper #SystemDesign #ProgrammingTips #TechCommunity #CodeWithShivam
To view or add a comment, sign in
-
🚀 Spring Tip: Mastering Context Hierarchies! 🚀 Did you know that Spring MVC lets you create a powerful context hierarchy? With a root WebApplicationContext for shared infrastructure (think: data repositories, business services) and child contexts for each DispatcherServlet, you can keep your app modular, maintainable, and DRY! 🌱 This means you can share beans across servlets, but still override or specialize them where needed. Whether you’re using Java config or classic web.xml, Spring’s flexibility has you covered. Ready to level up your Spring architecture? #SpringFramework #Java #WebDevelopment #BestPractices
To view or add a comment, sign in
-
✋ Nested ifs are not logic. Every time you open another bracket, you dig one layer deeper into the ruins of readability. Clean code is not about being smart. "It’s about leaving the next developer with fewer nightmares." Simpler doesn’t mean dumber — it means readable. 😶🌫️ If your code looks like a Russian nesting doll, it’s time for refactor. #CleanCode #dotnet #Java #backend #TheBackendFundamentals #architecture #DI #carbon.now.sh
To view or add a comment, sign in
-
-
In real-world projects, we often encounter scenarios where business logic varies based on dynamic conditions, such as different payment methods, discount strategies, or notification types. The Strategy Design Pattern offers a clean and powerful solution to these challenges. What is the Strategy Pattern? It is a behavioral design pattern that allows for selecting an algorithm's behavior at runtime. Instead of relying on complex if-else or switch statements, we encapsulate each behavior in its own class and let Spring manage them efficiently. For detailed implementation, you can refer to my post below. #SpringBoot #Java #DesignPatterns #CleanCode #SoftwareEngineering #SystemDesign #StrategyPattern https://lnkd.in/geTbcPga
To view or add a comment, sign in
-
🚀 Understanding @Async in Spring Boot — Simplify Asynchronous Processing! In real-world applications, performance matters — especially when handling time-consuming operations like sending emails, processing large files, or calling external APIs. That’s where Spring’s @Async annotation shines ✨ 👉 What is @Async? @Async allows you to run a method in a separate thread, freeing up the main thread to continue processing other tasks. Simply put, it helps improve application responsiveness and scalability. @Service public class EmailService { @Async public void sendEmail(String recipient, String message) { // Simulate delay try { Thread.sleep(3000); } catch (InterruptedException e) { } System.out.println("Email sent to: " + recipient); } } @SpringBootApplication @EnableAsync public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } Now, when you call sendEmail(), it will execute asynchronously without blocking the caller thread. 💡 Pro tip: • Use @Async carefully for methods that are independent and don’t need to return immediate results. • You can even return a CompletableFuture<T> to handle async results gracefully. ⸻ ⚙️ Use case examples: • Sending notifications or emails • Background report generation • Data synchronization tasks #SpringBoot #Java #Async #Multithreading #BackendDevelopment #PerformanceOptimization
To view or add a comment, sign in
-
🔹 Spring Tip: Where to Put @Transactional Many developers wonder: Should @Transactional go on repositories or service methods? Service Layer ✅ @Service public class UserService { @Transactional public void transferMoney(...) { ... } } Wraps multiple repository calls in one atomic transaction Ensures business logic consistency Supports propagation, isolation, read-only flags, rollback rules Repository Layer ❌ (usually) @Repository public interface UserRepository extends JpaRepository<User, Long> { @Transactional Optional<User> findById(Long id); } Each call starts its own transaction Adds overhead: dirty checking, flush, commit/rollback Breaks atomicity if multiple repo calls are made separately 💡 Best practice: Annotate service methods, not repositories. Use @Transactional(readOnly = true) for read-only queries. Profile first — small changes can give huge performance gains. #SpringBoot #Java #BackendEngineering #Transactions #JPA #Performance #SpringTips
To view or add a comment, sign in
-
Sravan Nalajala, Great statement 👍 Just to support what you’ve mentioned, * Repository methods in Spring Data are automatically transactional, so there’s no need to explicitly mark them with @Transactional in most cases. * But, the moment you move outside the repository layer. For example, to a service layer, a class/method that orchestrates multiple repository calls, Spring won’t automatically make that method transactional. You should explicitly use @Transactional at this level to ensure all operations participate in a single, consistent transaction. Spring team designed repository CRUD methods to be transactional by nature in order to guarantee correctness, consistency, and compliance with the JPA specification. If you’d like to explore this topic further, here’s a good read: https://lnkd.in/ea4BBSSF
Experienced Software Engineer with Proficiency in Java | SpringBoot | GCP | Microservices | Scala | AWS | RAG | AI | ML
🔹 Spring Tip: Where to Put @Transactional Many developers wonder: Should @Transactional go on repositories or service methods? Service Layer ✅ @Service public class UserService { @Transactional public void transferMoney(...) { ... } } Wraps multiple repository calls in one atomic transaction Ensures business logic consistency Supports propagation, isolation, read-only flags, rollback rules Repository Layer ❌ (usually) @Repository public interface UserRepository extends JpaRepository<User, Long> { @Transactional Optional<User> findById(Long id); } Each call starts its own transaction Adds overhead: dirty checking, flush, commit/rollback Breaks atomicity if multiple repo calls are made separately 💡 Best practice: Annotate service methods, not repositories. Use @Transactional(readOnly = true) for read-only queries. Profile first — small changes can give huge performance gains. #SpringBoot #Java #BackendEngineering #Transactions #JPA #Performance #SpringTips
To view or add a comment, sign in
-
Self Invocation bypasses Proxy Saw a few posts about this recently, here's what I got in my reading. 🔹 Bean Management All beans in Spring are managed by DefaultListableBeanFactory, which extends DefaultSingletonBeanRegistry. The DefaultSingletonBeanRegistry is the one that actually stores the bean instances — a map of bean name → object reference. 🔹 What Happens with Proxies When we use annotations like @Transactional or @Async, Spring doesn’t just enhance the bean. It creates a proxy (often a CGLIB subclass) and registers that proxy in the registry instead of the original instance. So when another bean calls it, the call goes like: Caller → BeanFactory → Proxy → Actual Bean The proxy gets the call, applies the advice (transaction, async, etc.), and then runs the actual method. 🔹 Why Self Invocation Breaks It When a method calls another method inside the same bean: method1() { method2(); // self-invocation } …the JVM doesn’t go through the registry again. The .class file already contains the direct bytecode reference for method2(). So the call becomes: this.method2() → skips proxy → advice never triggered 🔹 How to Fix It Use AspectJ instead of proxy-based AOP. AspectJ does bytecode weaving, literally modifying the .class file so advice logic is embedded — no proxy needed. Whether you actually need AspectJ is a separate decision — most of the time, the default proxy setup is good enough. #Spring #Java #AOP #Transactional #Async
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