Java Intern pool implementation creates too many temporary objects

212 views Asked by At

I have made an intern pool in java using the same idea as string intern. Simply put, I maintain a

WeakHashMap<T, T>

Every time when the map contains the object, it will return the same object, the benefit is it will save java heap memory. For example, I have a Person class like this:

public Person() {
    String name;
    int age;
    String employer;

    @Override
    public equals(Pbject obj) {
        ......
    }

    @Override
    public hashCode() {
        ......
    }
}

It doesn't have a field to make the class unique (No primary key). The problem is when I want to check if the map contains a specific person, I will need to create a temporary person first so that the map.contains() method can call the equals() method for this person. As a result, after I run profiler to see the memory usage, I can see that GC has collected a lot of temporary objects, it will surely result in more GC and CPU usage. Is there a way that we can implement the intern pool idea without creating too many temporary objects?

p.s. I got the intern pool idea from this post: Generic InternPool<T> in Java?

2

There are 2 answers

5
Serg M Ten On

A HashMap<T, T> is not a Map but a done something very weird to your equals() and hashCode() methods. As commented, creating a temporary short lived instance is cheap because the garbage collector uses generations. But what you must check for existence is the key not the object itself.

1
WJS On

I don't know what you're doing to use up a lot of heap memory but why not look at weak and strong references.

  • Weak references to a single object are kept around as long as there is a single hard reference. When the hard reference is garbage collected, so are the weak references.
  • Strong references will only go away when you start to run out of heap space. This would happen as you want to use more heap space for other objects. The older ones are GC'd.

So depending on what you are doing, you may want to check them out.