Uploaded image for project: 'Commons Lang'
  1. Commons Lang
  2. LANG-739

ToStringBuilder leaks memory if toString method causes hash code to be changed

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Open
    • Major
    • Resolution: Unresolved
    • 2.3
    • Review Patch
    • lang.builder.*
    • None

    Description

      We have the following abstract class:

      public class AbstractMessageItem {
      
          private String toString;
      
          public boolean equals(final Object obj) {
              return EqualsBuilder.reflectionEquals(this, obj);
          }
      
          public int hashCode() {
              return HashCodeBuilder.reflectionHashCode(this);
          }
      
          public String toString() {
              if (toString == null) {
                  toString = ToStringBuilder.reflectionToString(this);
              }
              return toString;
          }
      }
      

      We also have two concrete classes extending the above class and one of them has a reference to the other.

      Now, if we call toString() on the 1st one, this will in turn call toString() on the second one.
      The call to toString() on the second one will cause its hash code to be changed and as a consequence will also change the hashCode of the first one while computing its toString().

      This causes the infinite loop avoidance mechanism (i.e. the registry) to fail to unregister some objects and memory will be leaked.

      I believe that this leak can be avoided by using the system identity hash code when registering objects (as is done in HashCodeBuilder) instead of the user hash code.

      I know the issue can be worked around by removing the toString field (and loosing a dubious "performance enhancement" hack) or by making it transient, but I think that other "mutating" toString() methods can happen in the field (sometimes for good reasons) and fixing ToStringBuilder can be of help in some cases.

      Attachments

        1. LANG-739-patch.txt
          5 kB
          Woonsan Ko
        2. LANG-739-patch2.txt
          7 kB
          Woonsan Ko

        Activity

          People

            Unassigned Unassigned
            prenon Philippe Renon
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated: