在Spring Singleton中创建新实例会造成内存泄漏吗? [英] Will creating new instances in a Spring Singleton create memory leaks?

查看:161
本文介绍了在Spring Singleton中创建新实例会造成内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在维护一个应用程序,并注意到许多在Spring连接中定义为Singleton的对象在其方法中创建了其他对象的新实例。

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.

例如,每次调用login()方法时都会有一个LoginService Singleton创建一个新的LoginDetails实例。 LoginDetails是临时的,只有执行login()方法才需要。

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.

我的问题是,如果Spring为LoginService创建了一个对象,那么实例是什么LoginDetails曾经标记为垃圾收集作为对创建它们的对象的引用并且永远不会终止吗?

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?

我的意思是:

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?

我对Spring Singleton的理解是否正确?

Is my understanding of Spring Singleton correct?

谢谢

推荐答案

如果单例不维护对它创建的对象的引用(通过将它们存储在实例字段中) ),如果没有其他可达对象维护对这些对象的引用,则它们变得无法访问,垃圾收集器会收集它们。

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.

这篇关于在Spring Singleton中创建新实例会造成内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆