Clear memory unused object

Asked

Viewed 105 times

0

I have a set that contains millions of Strings and uses a lot of memory, the problem is that after I use it inside a foreach the memory used is not released, resulting in some executions of the method a java.lang.OutOfMemoryError. How can I free the memory of this object? I’ve tried to set it to null and run Runtime.getRuntime().gc;, but it is not releasing the memory.

public void saveAllData(Set<String> logSet, RegexEnum regexEnum) {
        Pattern dataPattern = Pattern.compile(regexEnum.getRegexPattern()[0]);
        Pattern urlPattern = Pattern.compile(regexEnum.getRegexPattern()[1]);

        Set<Log> logsToBeSaved = new HashSet<>();
        for (String log : logSet) {
            String data = getContentInLogLine(dataPattern, log, regexEnum.getGroupPattern()[0]);
            String url = getContentInLogLine(urlPattern, log, regexEnum.getGroupPattern()[1]);
            if (!StringUtils.isEmpty(data) && !StringUtils.isEmpty(url)) {
                if (url.contains("?")) {
                    url = url.substring(0, url.indexOf("?"));
                }

                logsToBeSaved.add(new Log(data, "/".concat(url), regexEnum));
            }
        }
        this.iLogRepository.saveAll(logsToBeSaved);
        LOGGER.info("Cleaning log objects.");
        logSet = null;
        logsToBeSaved = null;
        Runtime.getRuntime().gc();
    }

1 answer

1

Try calling your set’s clear() method, it would look something like :

public void saveAllData(Set<String> logSet, RegexEnum regexEnum) {
    Pattern dataPattern = Pattern.compile(regexEnum.getRegexPattern()[0]);
    Pattern urlPattern = Pattern.compile(regexEnum.getRegexPattern()[1]);

    Set<Log> logsToBeSaved = new HashSet<>();
    for (String log : logSet) {
        String data = getContentInLogLine(dataPattern, log, regexEnum.getGroupPattern()[0]);
        String url = getContentInLogLine(urlPattern, log, regexEnum.getGroupPattern()[1]);
        if (!StringUtils.isEmpty(data) && !StringUtils.isEmpty(url)) {
            if (url.contains("?")) {
                url = url.substring(0, url.indexOf("?"));
            }

            logsToBeSaved.add(new Log(data, "/".concat(url), regexEnum));
        }
    }
    this.iLogRepository.saveAll(logsToBeSaved);
    LOGGER.info("Cleaning log objects.");
    logSet.clear(); //Codigo implementado aqui
}
  • The clear method of Set calls the clear method of the internal Hashmap, which assigns null to each element of the map, would not be the same as what I am already doing? Even so I tested and unsuccessfully. I tried using a new Hashset<>(), unsuccessfully too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.