<programlisting><![CDATA[
public aspect InstanceTracking pertypewithin(org.xyz..*) {
-
- private Set<WeakReference<Object>> instances = new HashSet<WeakReference<Object>>();
+
+ // use WeakHashMap for auto-garbage collection of keys
+ private Map<?,Boolean> instances = new WeakHashMap<?,Boolean>();
after(Object o) returning : execution(new(..)) {
- instances.add(new WeakReference<Object>(o);
+ instances.put(o,true);
}
- public Set<Object> getInstances() {
- Set<Object> result = new HashSet<Object>();
- for(WeakReference<Object> ref : instances) {
- if (ref.get() != null) {
- result.add(ref.get());
- }
- }
- return result;
+ public Set<?> getInstances() {
+ return instances.keySet();
}
}
]]></programlisting>
<programlisting><![CDATA[
public aspect InstanceTracking<T> pertypewithin(org.xyz..*) {
- private Set<WeakReference<T>> instances = new HashSet<WeakReference<T>>();
+ // use WeakHashMap for auto-garbage collection of keys
+ private Map<T, Boolean> instances = new WeakHashMap<T, Boolean>();
after(T t) returning : execution(new(..)) {
- instances.add(new WeakReference<T>(t);
+ instances.put(t, true);
}
public Set<T> getInstances() {
- Set<T> result = new HashSet<T>();
- for(WeakReference<T> ref : instances) {
- if (ref.get() != null) {
- result.add(ref.get());
- }
- }
- return result;
+ return instances.keySet();
}
+
}
]]></programlisting>