Suppose all the objects in my problem setting has an ID
field, and I have a global map <ID, num>
that records the number of references that an object has. I have some other data (they are indexed by the ID
) that may occupy a lot of memory. Therefore, I need to regularly clear the data if the number of references to its belonging object is 0. How the map is updated is illustrated in the following example:
public void foo() {
MyClass obj1 = new MyClass();
// suppose obj.ID = 1;
// Now the globe map contains <1, 1> because the MyClass instance, whose ID is 1, has a reference obj1
MyClass obj2 = obj1;
// Now the globe map contains <1, 2> because the MyClass instance has another reference obj2
}
// When foo() terminates, the globe map contains <1, 0> because we can never access the MyClass instance through obj1 and obj2
The only problem I met is when an object is used as an argument to a system method invocation (e.g., list.add(obj)
), how can I know whether the object is referenced by something in the system method? Take the list.add(obj)
as an example, obviously obj
is referenced by something in the add
method. Otherwise, you can not use list.get(i)
to get that object.
Since the source code of the add
method is not in my application scope, I don't know how to update the counter in this case.
One solution is that we can delay the reduction of the counter of obj
when the reference to the list
is 0. But it is not a best solution in my problem setting. I hope to know if there are better solutions. Thanks in advance!