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?