DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Spring Boot: Cross-Origin AJAX HTTP Requests
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How To Build Web Service Using Spring Boot 2.x
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot

Trending

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • Simplifying Multi-LLM Integration With KubeMQ
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring: Serving Multiple Requests With the Singleton Bean

Spring: Serving Multiple Requests With the Singleton Bean

Read more about serving multiple requests with Spring beans!

By 
Vusala Hasanli user avatar
Vusala Hasanli
·
Jan. 15, 20 · Presentation
Likes (12)
Comment
Save
Tweet
Share
51.5K Views

Join the DZone community and get the full member experience.

Join For Free

Read more about serving multiple requests with Spring beans!


When I first started to learn Spring, two “difficult” questions crossed my mind:

  1. How is a singleton bean created?
  2. And how is that single bean auto-wired in different classes?

You may also like: Spring Bean Lifecycle

Imagine the following scenario:

There are two users. One of them wants to log in, and another one wants to create a report in our application at the same time. And both login and createReport methods use the userService bean, which is scoped as a singleton. In this case, do those methods use that singleton bean sequentially? Otherwise, how does a singleton bean serve multiple requests concurrently?

Answering these questions was not as difficult as I originally thought. It was only needed to clarify simple-yet-important points. That is why I will try to describe them with basic code examples. Let’s begin:

1. It would be useful if we talk about Spring containers first. Because I think this will help you to describe the process better in your mind.

The Spring container creates beans in it. After creating needed beans, it injects dependencies of them. The container gets its instructions by reading configuration metadata (XML or Java annotations). So after the Spring container is initialized, your application is ready to use as described in the following picture:

Photo of container on Spring documentation

When you define a bean definition like the following, you tell the container that it must create only one instance for that bean definition in the container:

 <bean id=”accountDao” class=”…” scope=”singleton”/>

This single instance is stored in a cache of such singleton beans. Then, the Spring container returns this cached object to all requests and references for beans with that bean definition:

Image title

If we want to show the above example with a new() operator for describing a simplified view of what Spring container does on startup of the application, we can code as following:

Java
 




xxxxxxxxxx
1


 
1
UserService userService = new UserService();
2

          
3
UserController userController = new UserController();
4
userController.userService = userService;
5

          
6
ReportController reportController = new ReportController();
7
reportController.userService = userService



I think there is no need for more explanation. The example above shows how the same bean is used for different classes.

2. In Spring, every request is executed in a separate thread. For example, when two users want to log in at the same time, the JVM creates two threads: one thread for the first user and another one for the second user.

For showing this, the following simple code snippet can help us. If you sent two requests for login method concurrently and print current thread name (which the requested login method is executed), you will see two different thread names there. This shows us every request is executed in a separate thread:

Java
 




xxxxxxxxxx
1
12


 
1
@RestController
2
public class UserController {
3

          
4
    @Autowired
5
    private UserService userService;
6

          
7
    @GetMapping(value = "/login/{username}")
8
    public User login(@PathVariable(value = "username") String username){
9
        System.out.println(Thread.currentThread().getName() + " ----------- " + username + " ----------- " + new Date());
10
        return userService.login(username);
11
    }
12
}



Java
 




xxxxxxxxxx
1


 
1
Result:
2
http-nio-8080-exec-9 ----------- Ben ----------  Sat Nov 23 20:01:35
3
http-nio-8080-exec-6 ----------- Kate ---------- Sat Nov 23 20:01:35 
4

          
5
You can send concurrent requests with help of curl command like this:
6
curl  http://localhost:8080/login/Ben & curl http://localhost:8080/login/Kate



And these threads work with the singleton bean separately. How? Let’s speak about memory allocation in Java a little bit.

In Java, every object is created in heap. Heap has globally shared memory. That is why every thread can access objects in heap.

But the stack is used for the execution of only one thread. In that thread, when a method is invoked, a new block is created in the stack in LIFO( Last-In-First-Out) order. This block holds local primitive values and references to other objects in the method. And the stack memory cannot be accessed by other threads.

So, when we create a singleton bean, it resides in heap. Because the heap is accessible from anywhere in the application, every created thread can point to that singleton bean. And how is this happening? When the thread requests the singleton bean, it is going to refer (with help of reference variable in the stack) to the bytecode of singleton bean in heap. So, multiple threads can refer to the singleton bean at the same time. The compiler is going to point to the same bytecode and simply execute it and store method-specific values in corresponding blocks in stack separately. There is no restriction preventing the compiler from doing this. The only restriction that the singleton class puts on the JVM is that it can have only one instance of this class in the heap. And this is why ideal singleton bean must be stateless. Otherwise, concurrency issues can occur.

I hope this will help you to understand the process clearly. If you have any questions, please let me know in the comments.

Happy coding!

Further Reading

Spring Bean Lifecycle

An Interview Question on Spring Singletons

Spring Framework Requests

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot: Cross-Origin AJAX HTTP Requests
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How To Build Web Service Using Spring Boot 2.x
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!