Marcin Cylke
Marcin Cylke

Reputation: 2066

Keeping track of already seen objects

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:

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?

Upvotes: 2

Views: 177

Answers (2)

dcernahoschi
dcernahoschi

Reputation: 15240

Just a completion to Brian Agnew correct answer. There is no WeakHashSet class in java API, you'll need to create it from a WeakHashMap like this:

Set<Object> weakHashSet = Collections.newSetFromMap(
        new WeakHashMap<Object, Boolean>());

See Collections.newSetFromMap java docs.

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272297

WeakReferences are the way to go. From here:

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself.

i.e. keeping a WeakReference won't force the JVM to hold a reference to this object.

Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

Upvotes: 5

Related Questions