How concurrency works in SpringBoot when the default lifetime of objects is singleton - spring-boot

In ASP.NET the default lifecycle of objects created in IoC container is per web request. While learning SpringBoot + Webflux, I found that the default lifecycle (Bean, Repository, Service, etc) created by the IoC container is singleton. I know I can change the default scope like this:
#Scope("prototype")
but I have not yet found an example where it would be used. So if IoC creates all object as singletons, how come there are no problems with concurrency. Can someone please explain this to me.

It's a good question. Generally speaking where concurrency is an issue, for example a transaction context in the database layer, springbook uses a thread based locking mechanism. See for example 1.2. Understanding the Spring Framework Transaction Abstraction. Otherwise, yes, anything injected with CDI is a singleton unless specifically annotated otherwise. That means that you should not keep state variables in your #Component or #Service classes. As long as the methods use only parameters passed in or variable local to the method concurrency isn't an issue because ever variable is created on the stack which is unique for each call. I have seen an application work great up until the day two people log in at once.
If you have to have a class with state variables you need to do a new of that class.
Each spring-context is created with a unique thread, so where objects are created or injected that are not stateless then state information is attached to the spring-context which runs in its own thread.
See also How does Spring bean Handle concurrency

Related

Why does spring use ioc and di?

I'm new to spring 5 and my question is why does spring use DI and IOC? I mean why do we have to write the beans in an XML (legacy) and then create it where we need it? Why don't we use one method instead that gives us that object, until we want to use this complex mechanism that happens in the spring container?
And another question is, does not reading XML slow down the program? Because we are reading from the hard disk anyway.
Note: It is true that we can use annotations, but for now I want to ask a question about reading from xml.
Spring IoC Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML) or Java Code or Java Annotations and Java POJO class. These objects are called Beans. Since the Controlling of Java objects and their lifecycle is not done by the developers, hence the name Inversion Of Control.
More on link HERE
As for your first part of the question.
why does spring use DI
To allow the developer to keep his code loose, and not entagle classes, it keeps your code clean.
In object oriented design, the amount of coupling refers to how much the design of one class depends on the design of another class. In other words, how often do changes in class A force related changes in class B? Tight coupling means the two classes often change together, loose coupling means they are mostly independent. In general, loose coupling is recommended because it's easier to test and maintain.
You may find this paper by Martin Fowler (PDF) helpful.
I mean why do we have to write the beans in an XML (legacy) and then create it where we need it
Note: We write the bean in XML and it is created when application starts when it looks at bean defintion, techinally you are never creating a bean, you are fetching only created bean from Spring Container(IOC) that Spring created for you when you started your application.
We are writing bean blueprint, or just bean, so that it can be constructed, placed in the Spring Container when the application starts, and then we have it at our disposal that we can fetch it using getBean method.
The whole point of "why", is because by default all beans are scoped as singleton, that means, when you fetch a bean, and do with it whatever you want, you do not worry about memory or anything, Spring takes care of the beans for you if they are scoped as a Singleton.
Second question:
And another question is, does not reading XML slow down the program? Because we are reading from the hard disk anyway.
There is no difference in performance between annotation or XML, it is just a different approach, I am not sure what you mean by "reading from hard disk", but one way or another you will have to configure your application, yes, many forums prefer to run away from XML, but in my honest opinion the only reason for that is because when you write a bad configuration in XML it is lot harder to find it compared to configuration in Java that will throw an exception.
XML, application.properties files require a redeployment of the application, while annotation and java configuration require recompilation of your project, so both of them have "flaws", but it is normal and quite understandable to me.
But in the end I believe that it is a matter of preference, I know personally quite a few people that combine annotations with XML configuration and they know lot more about Spring compared to me.
So in summary, it is pain to write beans and their configuration, same as you can write a class with methods without creating an interface for it since the result will be the same, but it will help you in the long run since you do not have to worry about memory or if you destroyed that bean or if you did not.
It would be nice that you read about
1.Lazy initialization of beans
2.Eager initialization of beans
3.Singleton scope of beans
4.Prototype scope of beans

Where spring container will create all run time objects

As per Spring documentation it says that spring IOC container manages entire life cycle for beans.
My question is where the Spring container will create a new object? in JVM or where? Also how references of objects will be maintained.
Also below questions,
For standalone application where those bean will be created?
For WebApplication where those bean will be created?
I have gone through major of the Spring doc's but haven't found any clear idea on how object references are maintained.
Since a Spring Boot application runs in a JVM, the objects are created there as well.
Spring keeps references to the beans in the application context. There are several concrete implementations of the ApplicationContext interface (depending on the type of the application), but in the end it comes down to a bunch of HashMaps, which hold the bean instances or information about how to create them, bean types etc. The most relevant class, if you're interested in implementation details, is IMO org.springframework.beans.factory.support.DefaultListableBeanFactory. This is used by all application context implementations to register beans, resolve them etc.

How do I get one common instance of ApplicationContext using Spring in Java

I know that Spring is most useful for dependency injection. But what I don't understand is how do I have one common "ApplicationContext ac=....." for the whole project, lets say I have a WebApplication and it has multiple number of packages but all of them still in one project , so how do I make the ApplicationContext instantiate only once. I had read somewhere that in Spring objects are initialized only once something as singleton beans but what I dont understand is that how is it different than Singleton design pattern, there is one question on this in SO but I couldn't quite clearly understand the answer as I am a newbie to Spring trying to learn by myself. Any help would really be appreciated. Sorry if the Q is too long. Hope I was able to explain my doubt clearly.
Spring veans are by default Singleton, although it is possible to configure them as prototype which means that a new bean will be created upon each request. In practice, singleton means one instance per context and are their lifecycle is managed by Spring nwhich also provides hooks into the various stages. Spring does not manage prototype beans once they have been created.
It is common in a SpringMVC application to have more than one context (one for the business services, the other for the web controllers). You would only need to create an ApplicationContext when building a standalone application. SpringMVC applications use the ContextLoaderListener to create the necessary contexts.

Spring core container is the basis for complete Spring framework?

All websites state that the Spring core container is the basis for complete Spring framework i.e., it is used across
the all modules like AOP, JDBC module, Web module, etc. As per my understanding, the Spring core container's main purpose is
to inject dependencies, so avoiding the need of factory classes and methods. Is that correct?
Second question: When it is said, Spring core container is the basis for complete Spring framework (e.g., for Spring AOP). As per my understanding, in Spring AOP also, getting the object of classes like
ProxyFactoryBean is achieved by core container. Right?
Thirdly, it is stated that Spring core container avoids the need for programming the use of singletons. How come singleton
classes are avoided by core container?
yep
yep
All beans declared in Spring config files are singleton by default. They are instantiated when your application starts.
First off, your understanding of what you get from Spring is about right. So let's get on to your third question, the interesting one.
The key is it's not that you don't have singletons, it's that they're singletons by configuration. This is a vital difference, as it means you can avoid all the complicated singleton enforcement code (the source of frequent problems) and instead just write exceptionally simple programs that focus on the business end of things. This is particularly important when you are writing a program with non-trivial object lifetimes: for example, in a webapp it makes it very easy to manage the lifespan of objects that hold state associated with a user's session, since if the objects have session scope, they'll be “singleton per user session”. That's enormously easier to work with than many of the alternatives.
The fact that Spring can also help out with transactions is just perfect as transaction handling is distinctly non-trivial, and AOP is the best solution to them in Java that I've seen (other languages have other options open) with Spring supporting a pretty straight-forward way of doing it. Try to do it properly without if you don't believe me. Spring's pretty much wonderful.

Should service layer classes be singletons?

I am using Spring framework. Should my service classes be created as singletons? Can someone please explain why or why not? Thanks!
Yes, they should be of scope singleton.
Services should be stateless, and hence they don't need more than one instance.
Thus defining them in scope singleton would save the time to instantiate and wire them.
singleton is the default scope in spring, so just leave your bean definitions as they are, without explicitly specifying the scope attribute.
You can read more about scopes in the spring docs.
Spring is easier to use if you stick with singleton-scoped beans. Singletons are its "default position", if you like. Yes, it supports other scopes (using scope="xyz" in the XML file), but it makes things harder to use and hurts performance.
Essentially, unless you have a good reason to do otherwise, stick with singletons.
You need mostly singletons. (Spring default.) Singletons must be thread-safe, because parallel requests will use the same single instance. In fact, they must be completely stateless, because it can be destroyed and recreated at any time.
If you need to keep track of state inside of your bean (you should not, this should be in the database or stored in the request), you will get many instances of the same type of bean, memory usage goes up with the number of requests, whereby with singletons you will still have just one instance.
Even if you scope you beans to a request, they must still need be at least thread-safe (requests coming from the same browser at the same time).
Service layer should be Singleton, otherwise for every incoming request a new object will be created and these objects are heavy contains business logic and lots of line of code. They must be Singleton.

Resources