Spring + Thread safe singletons - spring

I'm working on a project where we use MULE and Spring. In the context we create beans that provide the services. All the beans are essentially thread safe singletons. Is this a popular/recommended way of writing services?

By default a bean in spring will be a singleton and it is a very common scenario you describe.

Might be problematic performance wise. If you have many threads competing for the same service. The bean is defined thread safe, so acess from different threads would be effectively serialized.

In our RESTFul service we set up our entry points on a
#com.sun.jersey.spi.resource.PerRequest
basis and
#org.springframework.context.annotation.Scope("request")
which keeps our throughput up but we monitor to ensure that GC is good enough not to bloat the app.
Spring singletons are inherently thread-safe plus this is the default scope -- which performs quite well as we use them in all our web apps.

Related

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

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

Can i use ExecutorService in an ejb?

I have a scenario in which the results of various students are generated from within one ejb call by looping over the student list. I was thinking of creating threads for processing each student using executorService within a ejb call. Currently i just look up my ejb once.
i think this post should answer your question
EJB's and Threading
in general an EJB should not spawn new threads or do 'handcrafted' asynchronous execution.
In EE 7+ servers, you should just use JSR 236, which let's your application have access to executors/pools that are managed by the application server.
Otherwise, in theory, the EJB spec does not allow EJBs to create their own ExecutorService, which would create/manage its own threads:
The enterprise bean must not attempt to manage threads. The enterprise
bean must not attempt to start, stop, suspend, or resume a thread, or
to change a thread’s priority or name. The enterprise bean must not
attempt to manage thread groups.
These functions are reserved for the EJB container. Allowing the
enterprise bean to manage threads would decrease the container's
ability to properly manage the runtime environment.
In practice, it might work if you have complete control over the server running your application (you know which other applications are running and how many threads/pools they're creating in order to avoid overloading the system), and you limit the actions taken in those threads (for example, java:comp lookups won't work, transactional behavior might be limited, etc.).

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.

Clustering on tomcat with spring

I have a Spring web application with singleton services. There're also some singleton variables such as map with session data for all authenticated users and so on.
That all works nice on one server, but how could this system be distributed between a few servers?
The system runs on Tomcat.
Terracotta has Spring support and makes sure it's only one singleton bean among all the instances in the Terracotta cluster.
All you need to do is to enable Terracotta and declaratively add the singleton beans to the cluster.
If you bother to register a community account, you can read more in their online documentation.
maybe In a Tomcat cluster, how to share beans in an application? will help you further
That's one of the reasons that singletons are considered stupid or harmful. Have a look at Google Singleton Detector. This is a tool that detects singletons in java byte code. Consult the FAQ to see what are the problems with singleton.
If you want to cluster your application avoid the use of singletons. Consider persisting state into a database.

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