CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Aug 2017
    Posts
    2

    Effect on garbage collection of class with no explicit hashCode() and equals() method

    I've read that a (custom) class created without overriding hashCode() and equals() methods can lead to memory leaks. Specifically, putting an object of such a class into a HashSet twice will result in the first object leaking because replaced by the second object (whose hash code isn't different?).

    For example, ...

    Code:
    public class Key
    {
      public String key;
      public Key( String key ) { Key.key = key; }
    }
     
    @Test( expected = OutOfMemoryError.class )
    public void test_willLeakMemory()
    {
      Map< Object, Object > map = System.getProperties();
     
      while( true )
        map.put( new Key( "key" ), "value" );
    }
    How and why is this the case?

  2. #2
    Join Date
    Feb 2017
    Posts
    674

    Re: Effect on garbage collection of class with no explicit hashCode() and equals() me

    Quote Originally Posted by windofkeltia View Post
    I've read that a (custom) class created without overriding hashCode() and equals() methods can lead to memory leaks.
    This is not true. Java never leaks memory (unless there's a bug in the garbage collector).

    Some containers simply don't store duplicates. If you try to insert an object that already exists it either bounces or replaces the existing one (neither is a memory leak).

    What applies for a particular container is described in the Java API specification including exactly how the container decides whether two objects are equal or not.
    Last edited by wolle; August 18th, 2017 at 04:56 PM.

  3. #3
    Join Date
    Aug 2017
    Posts
    2

    Re: Effect on garbage collection of class with no explicit hashCode() and equals() me

    Thank you. I thought this wrong-headed, but the author seemed quite sincere and knowledgeable.

  4. #4
    Join Date
    Feb 2017
    Posts
    674

    Re: Effect on garbage collection of class with no explicit hashCode() and equals() me

    The only situation that is vaguely reminiscent of a memory leak in Java is what's referred to as "involuntary object retention". This happens when programmers hold on to objects they though they'd let go. Typically it may be objects stored in a static array. Such objects will never be reclaimed by the GC unless they're actively "nulled". If you keep adding objects you will get the dreaded "heap overflow" message eventually, typical of a memory leak.

    Note that both equals() and hashCode() have default implementations (in the Object class) based on object identity (rather than object content.) It means that the object references are compared to establish equality (and not some data the objects hold), so

    if (p1.equals(p2)) .....

    will be the same as

    if (p1==p2) ......

    That's what you get if you don't override equals() (and hashCode()).
    Last edited by wolle; September 11th, 2017 at 01:17 AM.

  5. #5
    Join Date
    Aug 2017
    Posts
    36

    Re: Effect on garbage collection of class with no explicit hashCode() and equals() me

    The GC (Garbage collection) in Java these days is very smart and everything should be cleaned up very shortly after it is no longer reachable. This is just after leaving a method for local variables, and when a class instance is no longer referenced for fields.

    Explicitly setting a reference to null instead of just letting the variable go out of scope, does not help the garbage collector , unless the object held is very large.

  6. #6
    Join Date
    Feb 2017
    Posts
    674

    Re: Effect on garbage collection of class with no explicit hashCode() and equals() me

    Quote Originally Posted by Priya456 View Post
    Explicitly setting a reference to null instead of just letting the variable go out of scope, does not help the garbage collector
    Is this is in reply to my previous post?

    What you say is true but it doesn't apply to static variables because they never go out of scope. This puts you in a position where you may need to actively "null" a reference to release the object for garbage collection. To "null" can mean setting a static reference to null but it can also mean removing a reference from a statically held data structure. The situation called "involuntary object retention" happens when you fail/omit to do this. Then objects may accumulate over time and this is very similar to a memory leak in principle.


    , unless the object held is very large.
    What do you mean by this? Why would it be beneficial to set references of large objects to null.

    Trying to "help" the GC is never a good idea regardless of the size of the object. And that's not what "nulling" in the "involuntary object retention" case is about. It's about actively releasing objects that are held in global scope because otherwise they would never be eligible for GC.
    Last edited by wolle; September 10th, 2017 at 01:10 AM.

  7. #7
    Join Date
    May 2025
    Posts
    1

    Re: Effect on garbage collection of class with no explicit hashCode() and equals() me

    Consider if a class in Java doesn?t have its own hashCode() and equals() methods, it will just use the default ones from the Object class. This actually means that object comparisons are based on memory addresses.

    The hash code is derived from the object's identity, not from its content.

    In garbage collection, this behavior doesn?t have a direct impact on how the GC identifies and clears objects. If there are no active references pointed to an object, then it will become eligible for GC.

    Suppose the objects are stored in these two methods, then there is a probability that an issue may still occur. Without using these methods properly, we cannot expect to see the removal of unused objects. This can lead to a memory leak.

    So in this case its not affecting how GC works, still not overriding these methods can indirectly cause objects to linger in memory longer than intended.
    Last edited by 2kaud; May 23rd, 2025 at 03:28 AM. Reason: Web link removed

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured