I’m trying to implement an interceptor for my application, that would be able to keep track of objects it has seen. I need to be able to tell, whether the object I’m seeing now is something new, or a reused one.
Assuming I have an interface like this one:
public interface Interceptor {
void process(Object o);
}
I’ve been thinking about adding a Set that would keep track of those objects. But since I don’t want to cause memory leaks with that kind of behavior, perhaps I should devise some other pattern? In the end, those objects may be destroyed in other layers.
Possible solutions seem:
- putting hashCode of an object into the Set
- using WeakHashSet instead of HashSet
the first option seems not 100% reliable, because hashCode may not be unique. As for the second option, I’m not that sure this will prevent memleaks.
And one more note, I’m not able to modify the objects, I can’t add fields, methods. Wrapping is also not an option.
Any ideas?
WeakReferencesare the way to go. From here:i.e. keeping a
WeakReferencewon’t force the JVM to hold a reference to this object.