开发者

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

开发者 https://www.devze.com 2023-03-28 13:17 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消