Spring and synchronization for part of the method - java

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.

Related

Singleton's other members

My question is broad, so I've split in two parts, and tried to be as specific as I can with what I know so far.
First part
A singleton holds a private static instance of itself. Some questions about singletons:
1. Should it's members also be static, or does that depend on the requirements?
2. If the answer to 1. is unequivocally yes, then what would be the point of having a private instance variable to begin with, if all members belong to the class?
3. Is the private instance needed because the JVM needs a referable object (THE singleton) to hold on to for the length of its (JVM's) life?
Second part
There is a requirement to make multiple concurrent remote calls within a tomcat hosted web application (the app utilizes GWT for some components, so I can utilize a servlet for this aforementioned requirement if a good solution requires this). Currently, I create an executor service with a cached thread pool into which I pass my callables (each callable containing an endpoint configuration), for each individual process flow that requires such calls. To me it would make sense if the thread pool was shared by multiple flows, instead of spawning pools of their own. Would a singleton holding a static thread pool be a good solution for this?
One note is that it is important to distinguish between the concept of a singleton (a class/object that has only a single instance) and the design pattern which achieves this via a class holding a single static instance of itself accessible in the global static name space. The concept of a singleton is frequently used in designs, the implementation of it via the singleton design pattern, however, is often frowned upon.
In the below, singleton is used to refer to the specific design pattern.
Part 1
A Singleton's members do not need to be static, and usually are not.
See 1.
A singleton (design pattern) requires an instance to itself in order to return that instance to users of the singleton, as well as keeping a reference to itself active to avoid garbage collection (as you suggest). Without this single instance, the object is essentially not an implementation of the singleton design pattern. You can create a class for which you only create a single instance and pass this class around where it is required (avoiding the global static namespace), and this would essentially be a recommended way to avoid using the singleton pattern.
Part 2:
Sharing your thread pools is probably wise (but depends on your requirements), and this can be done in a number of ways. One way would be to create a single pool and to pass this pool (inject it) into the classes that require it. Usual recommendation for this is to use something like Spring to handle this for you.
Using a singleton is also an option, but even if your thread pool here is encapsulated in a singleton, it is still generally preferable to inject this singleton (preferably referenced via an interface) into dependent objects (either via a setter or in their constructor) instead of having your objects refer to the singleton statically. There are various reasons for this, with testing, flexibility, and control over order of instantiation being some examples.
A Singleton's members need not be be static.
Invalidated by answer to point 1.
The instance of itself that the singleton need not be private either. You need an instance stored to a static member (public or private) if you have any other non-static member on the singleton. If there is any non-static member(it depends on your requirement) , then you need an instance to access that member(yes, JVM needs a referable object if the member is non-static)
Singleton member doesn't need to be static
Look at point 1
Singleton instance must be static (of course) and must be accessed by a static method; in addiction must have a private constructor to prevent new instance to be created
public class SingletonNumber10 {
public static SingletonNumber10 getInstance() {
if(null == instance) {
instance = new SingletonNumber10(10);
}
return instance;
}
private int number;
private static SingletonNumber10 instance;
private SingletonNumber10(int number) {
this.number = number;
}
public int getNumber() {
return this.number;
}
public static void main(String[] args) {
System.out.println(SingletonNumber10.getInstance());
System.out.println(SingletonNumber10.getInstance());
}
}
A singleton holds a private static instance of itself.
Not always, in fact, that's not even the best way to do it in Java.
public enum Director {
INSTANCE;
public int getFive() {
return 5;
}
}
Is a perfectly valid singleton, and is far more likely to remain the only copy in existence than a class that holds a private static instance of itself.
1. Should it's members also be static
No, the members should not be static, because then there is no need for a class, and therefore no need for that class to be a singleton. All static routines are subject to code maintenance issues, similar to C / C++ functions. Even though with singletons you won't have multiple instances to deal with, having the method off of an instance provides you with certain abilities to morph the code in the future.
2. If the answer to 1. is unequivocally yes.
It's not, so no need to answer #2.
3. Is the private instance needed because the JVM needs a
referable object (THE singleton) to hold on to for the
length of its (JVM's) life?
No, the private instance is needed because you have to have some ability to determine if the constructor was called previous to the access. This is typically done by checking to see if the instance variable is null. With race conditions and class loader considerations, it is incredibly difficult to make such code correct. Using the enum technique, you can ensure that there is only on instance, as the JVM internals are not subject to the same kinds of race conditions, and even if they were, only one instance is guaranteed to be presented to the program environment.
There is a requirement to make multiple concurrent remote calls within
a tomcat hosted web application (the app utilizes GWT for some components,
so I can utilize a servlet for this aforementioned requirement if a good
solution requires this). Currently, I create an executor service with a cached
thread pool into which I pass my callables (each callable containing an endpoint
configuration), for each individual process flow that requires such calls. To
me it would make sense if the thread pool was shared by multiple flows, instead
of spawning pools of their own. Would a singleton holding a static thread pool be
a good solution for this?
It depends. What are the threads in the pool going to be doing? If it's a thread to handle the task, eventually they will all get tied up with the long running tasks, possibly starving other critical processing. If you have a very large number of tasks to perform, perhaps restructuring the processing similar to the call-back patterns used in NIO might actually give you better performance (where one thread handles dispatching of call-backs for many tasks, without a pool).
Until you present a second way of handling the problem, or make more details of the operating environment available, the only solution presented is typically a good solution.
PS. Please don't expand on the details of the environment. The question submission process is easy, so if you want to expand on the second part, resubmit it as an independent question.

What is mean by STATE of a bean?

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

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

Should I use a pool of objects, a singleton or static methods in a multi-threaded environment?

I have a helper class that creates some objects, like a builder. The helper class does not have a state. It is on a multi-threaded environment; specifically, a web server. Is this class a good candidate for being a singleton?
What would be the difference between implementing this class as a singleton and just using static methods?
What would the effect of thousands of users accessing this object/these methods be?
I could make the class a regular class, but instantiating it every time it is needed would be a waste of memory.
Infact instead of singleton you can make the methods static.
Singleton doesn't have to be only 1, you can create a pool of instances and delegate work depending on the requirement, where as you don't have such control with static methods.
discussion on Singleton vs Static methods is here
As the name suggests, singletons are used to have only one instance of the object present at the time. So singleton does have a state, but you're accessing to that one state wherever you're calling your singleton.
So if you don't need any state saved in your class/method I'd suggest to use static approach.
No need to use singleton here (since you do not need a state), you can use static methods.
Singleton in principle offers more control by allowing a state. There won't be much difference in your case, but static methods will be easier to implement and use.
What would the effect of thousands of users accessing this object/these methods be?
Again, not much difference in both cases, but in Singleton you can have a state, and if you do not implement carefully, your code will be non-thread-safe. Every user calling the static method gets its own "instance" of the method (I think this is what you ask), so no risk of running into thread-safety problems there.
As has been stated before, given that your class doesn't have object state, static methods would work just fine.
However, consider the following - Depending on the overall design of your system, you may want to be able to specify a different implementation of the methods. This is usually done with either subclassing (...), or interface implementation (now the preferred method) - look up the strategy pattern. In either case, being able to provide alternte implementations would require you to not use static methods, but to have an (empty) object to call methods on.

static method and thread safety

Is the following code threadsafe ?
public static Entity getInstance(){
//the constructor below is a default one.
return new Entity();
}
Assuming the constructor itself is thread-safe, that's fine.
It would be very unusual for a constructor not to be thread-safe, but possible... even if it's calling the default auto-generated constructor for Entity, the base constructor may not be thread-safe. I'm not saying it's likely, just possible :)
Basically there's no magic thread-safety applied to static methods or instance methods or constructors. They can all be called on multiple threads concurrently unless synchronization is applied. If they don't fetch or change any shared data, they will generally be safe - if they do access shared data, you need to be more careful. (If the shared data is immutable or only read, that's generally okay - but if one of the threads will be mutating it, you need to be really careful.)
Only static initializers (initialization expressions for static variables and static { ... } blocks directly within a class) have special treatment - the VM makes sure they're executed once and only once, blocking other threads which are waiting for the type to be initialized.
It depends on the details of the Entity constructor. If the Entity constructor modifies shared data, then it is not.
It's probably thread safe, but what's the point? If you're just using a factory method to redirect to the default constructor then why not use the constructor in the first place? So the question is: what are you trying to achieve? The name getInstance() suggests a singleton (at least that's common practice), but you clearly don't have a singleton there. If you do want a singleton, use a static inner holder class like this:
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return InstanceHolder.INSTANCE;
}
private static final class InstanceHolder {
public static final Singleton INSTANCE = new Singleton();
}
}
but if you don't, why bother with such a factory method, as you're not adding any value (method name semantics, object pooling, synchronization etc) through it
Thread safety is about access to shared data between different threads. The code in your example doesn't access shared data by itself, but whether it's thread-safe depends on whether the constructor accesses data that could be shared between different threads.
There are a lot of subtle and hard issues to deal with with regard to concurrent programming. If you want to learn about thread safety and concurrent programming in Java, then I highly recommend the book Java Concurrency in Practice by Brian Goetz.
Multiple threads could call this method and each one will get an unique instance of 'Entity'. So this method 'per se' is thread safe. But if there is code in the constructor or in one of the super constructors that is not thread safe you might have a safety problem anyhow.

Categories