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.