|
1 | 1 | package name.abuchen.portfolio.snapshot.security; |
2 | 2 |
|
| 3 | +import java.lang.ref.WeakReference; |
3 | 4 | import java.time.LocalDate; |
4 | 5 | import java.util.ArrayList; |
5 | 6 | import java.util.Optional; |
@@ -49,13 +50,44 @@ public V get() |
49 | 50 | } |
50 | 51 | } |
51 | 52 |
|
| 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 | + |
52 | 80 | /** |
53 | 81 | * internal rate of return of security {@link #calculateIRR()} |
54 | 82 | */ |
55 | 83 | private final LazyValue<Double> irr = new LazyValue<>( |
56 | 84 | () -> Calculation.perform(IRRCalculation.class, converter, security, lineItems).getIRR()); |
57 | 85 |
|
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<>( |
59 | 91 | () -> PerformanceIndex.forInvestment(client, converter, security, interval, new ArrayList<>())); |
60 | 92 |
|
61 | 93 | /** |
|
0 commit comments