Will creating new instances in a Spring Singleton create memory leaks? - java

I'm currently maintaining an application and noticed that many of the objects that have been defined as Singleton in the Spring wiring create new instances of other objects in their methods.
For example there is a LoginService Singleton that creates a new instance of LoginDetails everytime the login() method is called. The LoginDetails are transient and are only required for the execution of the login() method.
My question is if Spring has created a single object for the LoginService how are instances of LoginDetails ever marked for garbage collection as a reference to the object that created them and used them is never terminated?
An example of what I mean is:
public void deleteCustomer(Long customerId, HttpServletRequest request) {
CustomerType customerType = new CustomerType();
customerType.setCustomerId(customerId);
CustomerDeleteRequestType deleteRequest = new CustomerDeleteRequestType();
deleteRequest.setCustomer(customerType);
CustomerDeleteResponseType deleteResponse = mmmwsClient.executeRequest(deleteRequest);
log.debug("Delete Response Recieved from Server for Customer Name Update " + deleteResponse.getServiceResult());
}
As the fields used are only method variables and not instance variables I guess the references to them would be destroyed when the method finishes?
Is my understanding of Spring Singleton correct?
Thanks

If the singleton doesn't maintain a reference to the objects it creates (by storing them in an instance field), and if no other reachable object maintain a reference to these objects, then they become unreachable, and the garbage collector collects them.
Who creates an object isn't important for the garbage collector. Who has a reference to an object is.

I honestly don't understand the question, but it is late at night so bear with me.
I looked at this page and it seems as though it does create a new instance every single time the method is called.
If you're using it like they are, a good replacement could be:
private static MessageResourceSingleton singleton;
public static MessageResourceSingleton getInstance() {
if (singleton == null) {
singleton = new MessageResourceSingleton();
}
return singleton;
}
I may not fully understand what you're getting at but if you could show us some examples of what you're using it would help a lot.

Related

How to create a session scoped thread safe object instance?

I want to have a resettable object instance for a session within my program that is thread safe, an example of a session might be a logged in user session.
I am currently doing something like this;
public final class ObjectFactory {
private static volatile NativeObjectWrapper instance = null;
private Singleton() {}
public static NativeObjectWrapper getInstance() {
if (instance == null) {
synchronized(ObjectFactory.class) {
if (instance == null) {
instance = new NativeObjectWrapper(AuthData);
}
}
}
return instance;
}
public void reset() {
synchronized(ObjectFactory.class) {
instance = null;
}
}
}
I want to have the object created lazily, with the ability to reset it. Is the above approach threadsafe? if not is there a common pattern to solve this?
An example again would be that scoped object here has some inner data based on the user session and therefore should be a new instance per user session.
Is the above approach threadsafe?
No, it is not.
Say we have two threads - A and B.
A calls getInstance(), passes the instance==null check, and then there's a context switch to B, which calls reset(). After B finishes executing reset(), A gets the context again and returns instance, which is now null.
if not is there a common pattern to solve this?
I don't remember seening singletons with a reset method, so I'm not aware of any common patterns for this problem. However, the simplest solution would be to just remove the first if (instance == null) check in getInstance(). This would make your implementation thread safe, as instance is always checked and modified within a synchronized block. In this scenario, you could also remove the volatile modifier from instance since it is always accessed from within a synchronized block.
There are more complex solutions I can think of, but I'd use them only if real-world profiling showed that you're spending too much time blocked on that synchronized block. Note that the JVM has some sophisticated ways of avoiding using "real" locks to minimize blocking.
One trickier approach could be to read the instance field just once:
public static Singleton getInstance() {
Singleton toReturn = instance;
if (toReturn == null) {
synchronized(SingletonFactory.class) {
if (instance == null) {
instance = new Singleton();
toReturn = instance;
}
}
}
return toReturn ;
}
But this could result in returning an old "instance". For example a thread could execute Singleton toReturn = instance and get a valid instance, then lose the CPU. At this point, a 1000 other threads could create and reset 1000 other instances until the original thread gets a spin on the CPU again, at which point it returns an old instance value. It's up to you whether such a case is acceptable.
Is the above approach threadsafe?
The answer depends on what you think "thread safe" means. There is nothing in your reset() method to prevent a thread that previously called getInstance() from continuing to use the old instance.
Is that "thread safe?"
Generally speaking, "thread safe" means that the actions of one thread can never cause other threads to see shared data in an inconsistent or invalid state. But what "inconsistent" or "invalid" mean depends on the structure of the shared data (i.e., on the design of the application.)
Another way of looking at it: If somebody tells you that a class is "thread safe," then they're probably telling you that concurrent calls to the class's methods by multiple threads will not do anything that disagrees with the class documentation and, will not do anything that disagrees with how a reaonable programmer thinks the class should behave in cases where the documentation is not absolutely clear.
NOTE: That is a weaker definition of "thread safety" because it glosses over the fact that, using thread-safe components to build a system does not guarantee that the system itself will be thread-safe.
Does everybody who uses your class clearly understand that no thread in the program may ever call reset() while any reference to the old singleton still exists? If so, then I would call that a weak design because it is very far from being "junior-programmer-safe," but I would grudgingly admit that, from a strict, language-lawyerly point of view, you could call your ObjectFactory class "thread safe."

Does Static Methods give bad results if two threads having own objects accessing same?

Does Static non synchronized Methods give bad results if two threads accessing same?
public class MySubjectUtils {
public static MyResponseClass createMyResponseClass(MyParameter record) {
if (record == null) {
return null;
}
MyResponseClass mRes = new MyResponseClass()
mRes.setName(record.getName());
mRes.setAddress(record.getAddress());
return mRes;
}
If two or more threads trying to access MySubjectUtils.createMyResponseClass(record); Will both gives results of their own or will they mix it up?
Since MySubjectUtils.createMyResponseClass(record) method creates a new instance of MyResponseClass(), each call to this method will create a new object. So each thread will receive its own object.
If your both threads are passing the same record object, actual contents of their MyResponseClass instances will be the same.
If threads are passing different instances of record object, their MyResponseClass instances will have different contents.
If the object record refers to is immutable, you don't need any synchronization in that method, since that's the only potentially-shared resource that the method references. Everything else is local to the method.
But if the object record refers to isn't immutable and it may be used across threads, it could be modified by another thread between this method's calls to getName and getAddress, leading to an invalid response.
So the answer is: You may or may not need synchronization, and if you do, how you implement it will vary. In both cases, it depends on the definition of the MyParameter class and how the object result references is used by the calling code.
It will not have any performance issues, and since the method is not accessing some shared resources, the threads will get their own unique result.

Releasing instance of a singleton in java

I am using a singleton created by the initialization-on-demand holder idiom.
When I´m done, I would like to "return" the singleton so that it can be used by other programs. Can I do this as follows...
Creating the Singleton
public class MyObject{
private MyObject(){}
private static class Holder{
private static final MyObject INSTANCE = new MyObject();
}
public static MyObject getInstance(){
return Holder.INSTANCE;
}
}
somewhere else I use this by
MyObject myObject = MyObject.getInstance();
// do something
myObject = null;
System.gc();
This accomplishes nothing:
myObject = null;
The singleton object will always be referenced by the final INSTANCE field in the Holder class, and it never will be GCd.
In fact, that's what "singleton" means. A "singleton" is a class for which only one instance is ever created, and the instance is never destroyed. If you want something else, then call it something else. Don't call it "singleton."
I bet you either want to use some form of mutual exclusion to prevent more than one thread from using the singleton at the same time, or else you want what #Newerth said: an object pool.
Also, this is obsolete: System.gc(); In the very early days of Java, it would bring everything else to a halt while the GC reclaimed all of the unused objects from the heap, but modern JVMs do continuous garbage collection in the background. The documentation for System.gc() has been changed to say that it's only a suggestion.
Yes that will work, but not sure why you need a holder class since your initialization is not costly (yet). If you are going to add more to the constructor later then fine, but otherwise it just clutters the code to have that other class.

Self releasing (reference counting) singelton

Consider the following scenario:
You have a singleton class that represent some sort of data provider.
This singleton class allocates a lot of memory,and you want it to release it's allocated memory when there is no one using him.
Flow:
Class A call getInstance and uses singleton (this is the first time getInstance called and singleton class allocates huge memory chunk)
Class B call getInstance and uses singleton
Class A and class B "dies" (no one using singleton now)
Program still running but singleton's memory is not released.
How do you suggest implementing singleton that at stage 3 (class A and B "dies") will free the memory (I know that java uses garbage collection but still lets say I want the following memory = null).
PS
I don't want to force each class that uses the singleton call release on singleton whenever it stops using it. I want the singleton to handle "releasing" memory by himself.
What you can do is
only create the singleton the first time it is asked for.
store it in a WeakReference. This will only stay alive after a GC if it is still has a "strong" reference elsewhere.
If the WeakReference.get() is null this means it was collected because no-one was using it strongly, another weak reference doesn't count. If it is needed again you need to recreate it and the WeakReference.
Like this,
public enum SingletonHolder{; // no instances
private static WeakReference<MyType> ref = null;
public static synchronized MyType getInstance() {
MyType type = ref == null ? null : ref.get();
if (type == null)
ref = new WeakReference<MyType>(type = new MyType());
return type;
}
}
BTW This assumes the instances which need this instance retains a reference to it. This is how the weak reference "knows" it is still needed.
BTW2 You don't need synchronized if it is single threaded but it should be harmless.
This means that you should call this method only when a new instance needs it for the first time, not every time and making it more performant shouldn't make much difference e.g. double checking just complicates it.
The use of the Design pattern: "Singleton" is very common and the common implementation is using a static reference.
The problem with this implementation is that many times it leaves floating garbage that is not in use.
For example:
A singleton that holds a DB connection pool that is only needed by the application at the start up for confing loading.
Therefor a better solution is an extension to the Singleton design pattern called WeakSingleton.
This pattern does the expected, when all other references to the original instance have expired the instance is cleaned.
An implemenation to this pattern in java is very simple and can be based on WeakReferences.
E.g. Code:
public class WeakSingleton{
static private WeakReference singleton; // instance
public WeakSingleton getInstance(){
WeakSingleton m = (WeakSingleton)singleton.get();
if( m != null)
return m;
synchronized (WeakSingleton.class){
m = (WeakSingleton)singleton.get();
if( m != null)
return m;
m = new WeakSingleton(); // creates new instnace
singleton = new WeakReference(m);
}
return m;
}
}

public static factory method

First of all please forgive me if its a really dumb question, I am just trying to learn this language to its core. I am reading Effective Java and the very first chapter talks about Static factory methods vs. Constructors. Their pros and cons. Few things that are confusing to me are:
class of an object returned by static factory method is nonpublic - what exactly does it mean?
unlike constructors static factory methods are not required to create a new object each time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?
Thanks.
class of an object returned by static factory method is nonpublic -
what exactly does it mean?
It means that the actual class of the objects returned by a static factory method can be a subclass of the declared type, and this subclass does not have to be public. It's just another implementation detail that client code should not care about.
unlike constructors static factory methods are not required to create a new object each > time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?
Yes, that's one way this could be done. But really, anything is possible.
First off, kudos to you for your choice in Java-lit: Bloch's book is an excellent primer.
To answer your 2nd question ('unlike constructors static factory methods are not required to create a new object each time they are invoked'), it's important to realize that what Bloch is saying here is that with a static factory you have the option of either: returning a new object or returning a pre-existing one. It all depends on what you want to do.
For example, let's suppose you have a really simple value class of type Money. Your static factory method probably should return a new instance -- that is, a new object with a specific value for Money. So, like this:
public class Money {
private Money(String amount) { ... } /* Note the 'private'-constructor */
public static Money newInstance(String amount) {
return new Money(amount);
}
}
But let's say you have some object that manages some resource and you want to synchronize access to that resource through some ResourceManager class. In that case you probably want your static factory method to return the same instance of itself to everyone -- forcing everyone to go through that same instance, so that that 1 instance can control the process. This follows the singleton-pattern. Something like this:
public ResourceManager {
private final static ResourceManager me = new ResourceManager();
private ResourceManager() { ... } /* Note the 'private'-constructor */
public static ResourceManager getSingleton() {
return ResourceManager.me;
}
}
The above method forces your user to only ever be able to use a single instance, allowing you to precisely control who(and when) has access to whatever it is you are managing.
To answer your first question, consider this (admittedly not the best example, it's pretty ad-hoc):
public class Money {
private Money(String amount) { ... }
public static Money getLocalizedMoney( MoneyType localizedMoneyType, String amount ) {
switch( localizedMoneyType ) {
case MoneyType.US:
return new Money_US( amount );
case MoneyType.BR:
return new Money_BR( amount );
default:
return new Money_US( amount );
}
}
}
public class Money_US extends Money { ... }
public class Money_BR extends Money { ... }
Note how I can now do this:
Money money = Money.getLocalizedMoney( user_selected_money_type );
saveLocalizedMoney( money );
Again, a really contrived-example but hopefully it helps you see more or less what Bloch was getting at with that point.
The other answers were good -- I just think that, as a beginner, sometimes it helps to see some actual code.
When you use the new keyword then you as the developer know that the JDK will create a new instace of that object. What the author is saying, when you use a static method, the developer no longer knows if the method is creating a new instance or possibly doing something else. Something else can be, reusing cached data, object pooling, creating a private implementation and returning a subclass of the class.
class of an object returned by static factory method is nonpublic
Frequently a static factory method will return either an an object typed as an interface (most common), or sometimes some base class (less common). In either case, you don't know the exact class of the returned object.
The advantage of this is getting an object whose behaviour you know without worrying about the messy details of what class it instantiates.
unlike constructors static factory methods are not required to create a new object each time they are invoked
To understand this, consider the case of working with a singleton. You may call .getInstance() on some factory classes to get the singleton instance of an certain object. Typically, what this does is create an instance of the object if it doesn't already exist, or give you the existing instance if it already does. In either case, you get back a copy of the object. But you don't (and won't) know if this singleton had to be created, or if one had already been constructed previously.
The advantage of this is that the lifecycle of the object and when it is created is managed for you.
Both of your questions can be answered by looking at some code that makes use of both of these properties of static factory methods. I suggest looking at Guava's ImmutableList.
Note how the no-arg factory method of() always returns the same instance (it doesn't create a new instance each time). If you look carefully, you'll also notice that its copyOf(Iterable) factory method actually returns the object that is passed to it if that object is itself an ImmutableList. Both of these are taking advantage of the fact that an ImmutableList is guaranteed to never change.
Notice also how various factory methods in it return different subclasses, such as EmptyImmutableList, SingletonImmutableList and RegularImmutableList, without exposing the types of those objects. The method signatures just show that they return ImmutableList, and all subclasses of ImmutableList have package-private (default) visibility, making them invisible to library users. This gives all the advantages of multiple implementation classes without adding any complexity from the user's perspective, since they are only allowed to view ImmutableList as a single type.
In addition to ImmutableList, most instantiable classes in Guava utilize static factory methods. Guava also exemplifies a lot of the principles set forth in Effective Java (not surprising, given that it was designed by those principles and with guidance from Josh Bloch himself), so you may find it useful to take a look at it more as you're working through the book.

Categories