What is mean by STATE of a bean? - java

It is generally said that choose only those beans as singleton that don’t have state. I am new to Spring and reading about bean scope in Spring.
My first query was what this STATE actually mean with respect to Bean?
Secondly, Why it is recommended to use singleton scope with only stateless bean? Is there some thread safe related limitations or Is there any other reason?

Any member attributes of class is referred to as its state.
Classes with no mutable state are best suitable for becoming a Spring (singleton) beans. Mutable state refers to those member attributes to which new values can be assigned after the object has been constructed.
Beans like DAOs which have member attributes such as JpaRespository can be considered to have fairly immutable state, as no one assigns new values to JpaRespository attribute once DAO object has been initialized.
Only beans which have no state (no member attributes) or have immutable state (member variables whose values are not updated once they have been assigned a value) are the ideal candidates for becoming Spring bean. This is because most Spring beans are configured as Singleton beans, and are used by multiple threads in the container. Imagine if you had mutable state and multiple threads were trying to update state of singleton bean, you will never have predictable result.
If your bean is not Singleton, but instead it is a Prototype bean, then, that bean can have state as such beans are created and destroyed as per need.

An object (and a bean is an object) has a state if the calls to methods do not only depend on the parameter given to the method call but also to the previous calls.
In principle if you have any instance variables you have likely a state. The only exception to this is that singletons stored in instance (not static) variables (which is quite usual in spring programming) don't count to the state.
When using a multithreaded environment a state in a singleton can have side effects. E.g. one thread sets the state (e.g. a connection to open) and another thread does not expect this state. Then one thread could fail.

In which state of object you want to run your program.When you design and write your class you do not know whether client use it as singleton OR prototype. The container configures object .So,it might be singleton OR prototype .For example TransactionAwareDataSourceProxy
class of spring framework is written to run in either protoype Or singleton.The class is written in such a way that it is safe from multithrading access .As the state that is shared by all threads is made common via DI container with some setter method.So,the configuration as singleton is made at startup via container and its common value is used by all threads Or single thread.The setting of instance variable is made only once with some setter method.
For example in class TransactionAwareDataSourceProxy there is reobtainTransactionalConnections as instance variable.
public TransactionAwareDataSourceProxy()
{
reobtainTransactionalConnections = false;
}
public TransactionAwareDataSourceProxy(DataSource targetDataSource)
{
super(targetDataSource);
reobtainTransactionalConnections = false;
}
public void setReobtainTransactionalConnections(boolean reobtainTransactionalConnections)
{
this.reobtainTransactionalConnections = reobtainTransactionalConnections;
}
These are the places in code where reobtainTransactionalConnections is iniatialized .If you decided to make this class singleton via DI container you set in once either with constructor injection OR setter injection.So,if we make setter injection then setReobtainTransactionalConnections will be either true Or false and remains same throughout the object life time.I think thats the advantages of configuring object with container ,the object state control can be easily made

Related

Actual business scenrio where we use Prototype scope in spring?

I was readign about differnt scopes for beans in Spring.
Everytime I have created bean in xml , I have never use scope property, which means It was SingleTon."
For prototype I read that " Prototype scope is preferred for the stateful beans"
What is meant by stateful beans?
Can someone give me realtime example, where we have prototype scope?
Since singleton is one instance for the whole application, and this object (I'm speaking about the patter, not even spring yet) if had some state for the example name. This field called name should be fine while just one thread calls the object. BUT singleton is one object for application as I said before.
A typical example in spring
#Component
MyComponent{
private String name;
public void editName(String newName)
{
name=newName
}
}
ASAP more than one thread call this bean, you will have race conditions (you should read about it ). That's why a singleton must not have state but could have other dependencies (dependency injection).
If you use prototype scope, spring will create one object per use, so in the example name will not be shared and there is any race condition, that's fine!!

Singleton - Spring Bean why not thread safe

I understand Object Creation and Thread safety are two different things.
Singleton is a way of constructing an object, some design pattern we follow to construct the object.
Spring Bean - Using Singleton scope, we guarantee that only 1 instance will be there, but still Spring bean is not thread safe.. why..??
Cannot be thread safe, precisely because just one instance is created, so every request(thread) will use the very same instance, so concurrency issues may happens.
If for example your scope is prototype, Spring wont use singleton and then it will create an instance per getClass invokation.
Same thing for request or session, instance will be created by request or per user session.
As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.
you can read in the documentation how it´s working
http://www.tutorialspoint.com/spring/spring_bean_scopes.htm

Java best way to share an object across other objects without using static

I have class A which instantiate class B which in turn do same for class C and so on, forming a large tree. I now need to instantiate an object that should be available all across the tree and I don't want to individually inject this object manually in all classes. I don't want to use a static because there could be different instances of class A running concurrently in different thread and this shared object must be unique per thread. I don't have much experience with thread safe operations.
Use Spring to manage the instance. That way you can inject your instance into any class that needs it and, provided the creation of the parent class is spring managed, the injected bean will be populated.
In some more detail, what you can do is define a class.
public class MyBean {
// Add your class details.
}
And ensure that Spring is either scanning its package or you have defined the bean in your applicationContext.xml file like this. The next stage is to inject this bean where you need to, using the #Autowired annotation..
#Autowired
private MyBean myBean;
And on the creation of that class, myBean will be populated with the same instance of MyBean that was initially created.
Advantages
Doing it this way means that your solution scales well. You can inject it anywhere without constantly changing constructors (and when you're creating more and more sub classes and relationships between classes, this is a prime candidate for Shotgun Surgery.
It's always good to learn about technologies that are used in industry.
Managing a single instance of a class using other methods (like the Singleton pattern) is usually a bad idea.
Disadvantages
Spring does a lot more than just inject objects, and you're pulling down a lot of classes to do just this, which will increase the size of your solution, although not significantly.
Extra Reading
Have a look at a basic Spring tutorial to get you going.
Have a look at the different scopes that you can create beans with, in case some of them suit your needs better.
You either need a local reference in the context that you want to use the object or you need a static reference. Since you don't want to use static you need to get a local reference. You can do this by passing the object in in the constructor or by adding a setter method. Then higher up the tree where ever you construct the child node you pass in the needed object.
You can have kind of a "Parallel Singleton" so to say, i.e. instead of having only one instance it will keep as many instances as there are threads, in a hashmap with a thread-related object being the key.

Best design to share class instance between many classes

I am going to create a utility Class APIUtility, it wraps a unique Object token generated by the server engine, once I used my username and password to get the Object token, I get the door is opening so I can access the engine anytimes if the token is still alive.
I want to use existing 'APIUtility' once I get the access to avoid unnecessary authentication effort. and with this 'APIUtility' I get directly call many functions to server engine. but right now, I have some else classes, they are under different place to take different responsibility: e.g. build data, logic validation, condition elevation, so these classes both need to have a base line use APIUtility to access engine data, do anybody have good design for this? because I fell it every class have a variable APIUtility we need set it for create a instance of these classes is not a good design.
You're on the right track in my opinion; simple is always best.
Just have all the classes that need APIUtility take an instance as a dependency in the constructor.
That way, if you need/want to, you can just instantiate APIUtility once and have it be shared.
FYI, this is what some people would call "poor man's dependency injection".
I would use dependency injection, Spring framework. Another option is to use Singleton pattern.
You should take a dependency injection\IOC framework like CDI or spring. I personally like CDI more but that is a personal choice.
With Dependency Injection a Container manages the associations between your classes. If you access a class that has elements inside that needs to be injected the compiler sets these through Constructor-Injection(Constructor) or Setter-Injection(Setter-Method).
I would use spring with dependency injection and a appropriate bean scope.
This is definitely a case for Inversion of Control or Strategy Pattern.
Overall though I would have to say that maybe your responsibilities are a little mixed up. Is there any reason it can't be a static util class (which takes a token as a parameter)? If no, then you might as well do that, if yes, you should probably think of a more useful name for the class.
You could use a variable of type ThreadLocal.
ThreadLocal can be considered as a scope of access, like a request scope or session scope. It's a thread scope. You can set any object in ThreadLocal and this object will be global and local to the specific thread which is accessing this object. Global and local? Let me explain:
Values stored in ThreadLocal are global to the thread, meaning that they can be accessed from anywhere inside that thread. If a thread calls methods from several classes, then all the methods can see the ThreadLocal variable set by other methods (because they are executing in same thread). The value need not be passed explicitly. It's like how you use global variables.
Values stored in ThreadLocal are local to the thread, meaning that each thread will have it's own ThreadLocal variable. One thread can not access/modify other thread's ThreadLocal variables.
Java Thread Local – How to use and code sample
e.g. You can have something like that:
public class APIUtility {
private static ThreadLocal<Engine> ENGINE_LOCAL = new ThreadLocal<Engine>();
public static void setEngine(Engine engine) {
ENGINE_LOCAL.set(engine);
}
public static Engine getEngine() {
ENGINE_LOCAL.get();
}
}
class NameValidator {
public void foo() {
Object obj = APIUtility.getEngine().getSomething();
}
}
See also:
Thread-local storage - Wikipedia, the free encyclopedia
Java Thread Local – How to Use and Code Sample | Javalobby

Spring and synchronization for part of the method

I have a manager as Spring wired bean. I believe every bean defined for spring by default is wired as singleton. I have some methods in this bean which I need to synchronize.
How should I be doing that then --
void zzz() {
synchronized (this) {
...
}
}
or
void zzz() {
synchronized (MyClass.class) {
...
}
}
?
The main difference in the two is that in the first case, the the instance of the class as the monitor and the second one uses the Class as the monitor.
The first one is probably the way to go in your case because, in the near future if you decide to have many instances of your class, their methods will be synchronized on the respective instances. As opposed to if you use a Class as a monitor, if one thread is calling a synchronized method on one instance, no other threads will be able to call methods (those that are synchronized) on any instances of the same class.
Unless you're accessing mutable static class variables (potentially nasty to begin with), the first is the appropriate way to synchronize.
Understand that while Spring is only creating one instance of a singleton bean and using it for anybody who has a dependency on a bean of that type, the singleton is not a static entity. There is no compiler constraint preventing you from instantiating that class yourself outside the Spring context. It's simply the only instance because Spring knows not to make more of them... not because it can't be done. The point I'm trying to make here is that it's iffy bordering on incorrect to draw a parallel between class-level data and the singleton's data.
In corollary, synchronization should occur on the narrowest scope possible. In your case, that means synchronize on the object instance containing the shared data rather than on the wider scope of the entire class.

Categories