Skip to content

Commit 06ed4ae

Browse files
committed
Keep only a weak reference to PerformanceIndex in security performance
Background: if users have selected a ttwror for a very long period, then caching the whole PerformanceIndex with the detailed data (dates, longs) eats up a lot of memory.
1 parent 73887a6 commit 06ed4ae

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

name.abuchen.portfolio/src/name/abuchen/portfolio/snapshot/security/LazySecurityPerformanceRecord.java

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package name.abuchen.portfolio.snapshot.security;
22

3+
import java.lang.ref.WeakReference;
34
import java.time.LocalDate;
45
import java.util.ArrayList;
56
import java.util.Optional;
@@ -49,13 +50,44 @@ public V get()
4950
}
5051
}
5152

53+
/**
54+
* The lazy weak value computes the value only when needed but also keeps
55+
* only a weak reference to it.
56+
*/
57+
private static final class LazyWeakValue<V>
58+
{
59+
private WeakReference<V> reference = new WeakReference<>(null);
60+
private final Supplier<V> computeFunction;
61+
62+
public LazyWeakValue(Supplier<V> computeFunction)
63+
{
64+
this.computeFunction = computeFunction;
65+
}
66+
67+
public V get()
68+
{
69+
var answer = reference.get();
70+
if (answer != null)
71+
return answer;
72+
73+
answer = computeFunction.get();
74+
reference = new WeakReference<>(answer);
75+
76+
return answer;
77+
}
78+
}
79+
5280
/**
5381
* internal rate of return of security {@link #calculateIRR()}
5482
*/
5583
private final LazyValue<Double> irr = new LazyValue<>(
5684
() -> Calculation.perform(IRRCalculation.class, converter, security, lineItems).getIRR());
5785

58-
private final LazyValue<PerformanceIndex> performanceIndex = new LazyValue<>(
86+
/**
87+
* weak reference to the performance index, because it can consume a lot of
88+
* memory in particular for large intervals
89+
*/
90+
private final LazyWeakValue<PerformanceIndex> performanceIndex = new LazyWeakValue<>(
5991
() -> PerformanceIndex.forInvestment(client, converter, security, interval, new ArrayList<>()));
6092

6193
/**

0 commit comments

Comments
 (0)