singleton pattern for microservices - spring

As per definintion of singleton pattern "
Ensure a class has only one instance, and provide a global point of access to it.
Encapsulated "just-in-time initialization" or "initialization on first use"."
How to create a Singleton object for distributed microservices using spring?

A Microservice can have one to many endpoint routed to a service which actually runs the business logic and replies back the end result via Controller. In reality these micoservice components run inside a container. Now if you want just one specific container for that service then don;t scale it. If it is deployed to run on kubernetes then make run like a daemonset. These are just the references that you can do that will make it act like a singlton container.

If you're talking about Singleton objects, you mean an instance of a class inside a microservice?
That's what Spring does: every Spring Bean is a Singleton by default.
That is: unless you have multiple instances of the java process, of course

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

Why use #Component annotation with each service in CQ

I am bit confused about following things. I understand #Service and #Component annotations are main annotations when we define a component or a service in OSGi. I am referring to http://felix.apache.org/documentation/subprojects/apache-felix-maven-scr-plugin/scr-annotations.html and What is the difference between OSGi Components and Services
Questions:
A service can not be created without #Component annotation, why is that?
I understand once we define a service its life-cycle is managed by OSGi differently but what are the advantages of doing so?
How do we use class defined as #Component as service can be accessed via sling.getService(ServiceName.class)
A service can be published without a #Component annotation, but you have to do it programmatically. If you use the annotation then you benefit from the automatic metadata generation in the build tool, and also from the Declarative Services runtime framework. This simplifies a lot of things. If you want to do it with low-level code you have to write an implementation of BundleActivator, declare that with the Bundle-Activator manifest header, call context.registerService etc. Bottom line: just use the #Component annotation!
Simple: laziness. When a component is a service then it can be instantiated lazily "on-demand", i.e. only when consumer first tries to use the service. Non-service components, on the other hand, usually do other kinds of things inside themselves, e.g. running a web server or a GUI or a polling thread, whatever. These need to be running all the time, rather than on-demand.
3. I didn't understand this question.
A component that is not published as a service cannot be accessed from outside the bundle. If you want it to be accessible then it has to be a service. In case you think this is useless, consider a component that creates an HTTP server. It opens port 80 and responds to network requests from the outside world. So it does something useful even though it's not a service and not accessible from other bundles. This kind of component is like a bridge between your application and the outside world; whereas services are a bridge between one part of your application and another part.
OSGi is the one where bundles are installed and manages. Everything that needs to be there in OSGi has to be a component be it simple component, a service or servlet. That is why we need to use #Component with service also.
Services are singleton. Everything that needs to be managed for Singleton class and using reference of service is done by OSGi. Nothing has to be done from our side. So everything is automatically managed.
You dont access components like that. Components are independently used. Quoting example from different post:
Suppose you want to a write Server component that sits on socket and responds to requests over TCP/IP. When the component starts, it opens the socket and creates the thread(s) required to serve clients. When it stops, it closes the thread(s) and socket

Single instance of an object per transaction

I have a use case, that theoretically seems to me as it would be a solved problem. But i'm not able to find a sure fired implementation.
I've created a RESTful API, using Apache CXF, Spring and Hibernate
This application encompasses a standard Service-Proxy-DAO layered structure
I need to instantiate a custom logger object at my service (or pre-service) layer and initialize a bunch of parameters which will remain constant, for the most part through every call that goes through my application layers and back.
How can i, for every individual service call, initialize this logger object once, and use it across all my layers without having to instantiate it everytime. Either i inject the initialized object in every class i need or something on those lines.
I don't want to use static blocks, or pass the object in method signatures.
Is there anything that i can use as a part of the Spring, CXF or other java framework that allows me to implement this use-case.
EDIT: I would define a transaction as a single call to a web service endpoint, from invocation to response.
ThreadLocal would be an ideal candidate to solve your problem.
UPDATE:
Creating a thread local that is available in all the places where this "shared" reference is required will give all these contexts access to this resource without having to pass the reference around.
see http://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/ - looks like a good explanation of how to use thread local and also deals with your problem space.

How to share bean INSTANCE across war in SPRING?

I want to share a singleton bean across multiple war. I know sharing ApplicaitonContext using parentContextKey attribute(Example, http://blog.springsource.org/2007/06/11/using-a-shared-parent-application-context-in-a-multi-war-spring-application/)
But this way instance of bean created multiple (for 2 war, 2 instance). I want only 1 instance across 2 war.
Another way, If i set some value in any POJO, it should be accessible in another war.
Reason i need this is, there are some beans(like HibernateSessionFactory, Datasource etc which are expensive) which are created multiple times(n instance for n war). Whereas i want to utilize same instance instead of creating same in different war.
Can anyone provide me solution for this?
You could achieve this by binding the objects into the global JNDI tree. That means that both WARs would have references to an object looked up in JNDI.
Hibernate allows you to use the hibernate.session_factory_name property (this may well be a good starting point. Data sources should already be looked up from JNDI.
One thing, I would not class a session factory or a data source as expensive, so you may well be saving a miniscule amount of memory in exchange for a lot of additional complexity, so I would ask myself the question on whether this is worth the additional maintenance headaches.
Spring provide a way to expose any bean (service) and these bean can be access from any other web application or any standalone application.
please refer Remoting and Web Service using Spring to get more details.

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