Search code examples
javaspringspring-bootdependency-injectionspring-ioc

In a Spring service, should I set null or empty lists used in the end of a method to save memory?


I am using spring boot (generated by JHipster) with some services that are using a List as field.
I was wondering wether I should empty or nullify this list at the end of the methods that use it.
Is there any impact on JVM memory ?
Considering this method can be called 100x + per day, and considering that each user has its own execution context so fields are not erasing previous ones as far as I understand.

Example :

package fr.vyvcareit.poccarto.service;

//imports

@Service
@Transactional
public class SiteService {

    //Liste temporaire pour repérer les doublons
    private List<String> siteCodesDansImport ;

    public SiteService() {  }

    public void preImportSiteError(List<Object> rows) {

        this.siteCodesDansImport = new ArrayList<String>();

        for (int i = 0; i < rows.size(); i++) {      
            checkSiteCode(int num_ligne, HashMap row);
        }
        // I'm all done, I do not need this.siteCodesDansImport anymore...
        this.siteCodesDansImport=null; // => Is this line important for java memory ???

    }

    private void checkSiteCode(int num_ligne, HashMap row){
        ...
        siteCodesDansImport.add(site_code);
        ...
    }
}

Any help would be appreciated !


Solution

  • By default, Spring beans has singleton scope. That means your service has single instance per application. Having fields on singleton beans is not thread safe and should be avoided.

    Every new request will override state of your collection and requests will be affecting each other states, which will lead to unpredictable behavior.

    Never ever store state into field variables of singleton beans.

    For your collection just use local variable. Pass it around via method parameters (e.g. into checkSiteCode). At the end execution, you don't need to set it to null. Java GC will take care of it.