Skip to content

Commit 4dc5142

Browse files
committed
Prevent cache from consuming too much memory
Change the cache in `CachingOperationInvoker` to be a reference based map and also clean stale entries when a specific threshold is met. Fixes gh-28313
1 parent adb9226 commit 4dc5142

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvoker.java

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,10 @@
1818

1919
import java.security.Principal;
2020
import java.time.Duration;
21+
import java.util.Iterator;
2122
import java.util.Map;
23+
import java.util.Map.Entry;
2224
import java.util.Objects;
23-
import java.util.concurrent.ConcurrentHashMap;
2425

2526
import reactor.core.publisher.Flux;
2627
import reactor.core.publisher.Mono;
@@ -30,6 +31,7 @@
3031
import org.springframework.boot.actuate.endpoint.invoke.OperationInvoker;
3132
import org.springframework.util.Assert;
3233
import org.springframework.util.ClassUtils;
34+
import org.springframework.util.ConcurrentReferenceHashMap;
3335
import org.springframework.util.ObjectUtils;
3436

3537
/**
@@ -45,6 +47,8 @@ public class CachingOperationInvoker implements OperationInvoker {
4547

4648
private static final boolean IS_REACTOR_PRESENT = ClassUtils.isPresent("reactor.core.publisher.Mono", null);
4749

50+
private static final int CACHE_CLEANUP_THRESHOLD = 40;
51+
4852
private final OperationInvoker invoker;
4953

5054
private final long timeToLive;
@@ -61,7 +65,7 @@ public class CachingOperationInvoker implements OperationInvoker {
6165
Assert.isTrue(timeToLive > 0, "TimeToLive must be strictly positive");
6266
this.invoker = invoker;
6367
this.timeToLive = timeToLive;
64-
this.cachedResponses = new ConcurrentHashMap<>();
68+
this.cachedResponses = new ConcurrentReferenceHashMap<>();
6569
}
6670

6771
/**
@@ -78,6 +82,9 @@ public Object invoke(InvocationContext context) {
7882
return this.invoker.invoke(context);
7983
}
8084
long accessTime = System.currentTimeMillis();
85+
if (this.cachedResponses.size() > CACHE_CLEANUP_THRESHOLD) {
86+
cleanExpiredCachedResponses(accessTime);
87+
}
8188
ApiVersion contextApiVersion = context.getApiVersion();
8289
CacheKey cacheKey = new CacheKey(contextApiVersion, context.getSecurityContext().getPrincipal());
8390
CachedResponse cached = this.cachedResponses.get(cacheKey);
@@ -89,6 +96,20 @@ public Object invoke(InvocationContext context) {
8996
return cached.getResponse();
9097
}
9198

99+
private void cleanExpiredCachedResponses(long accessTime) {
100+
try {
101+
Iterator<Entry<CacheKey, CachedResponse>> iterator = this.cachedResponses.entrySet().iterator();
102+
while (iterator.hasNext()) {
103+
Entry<CacheKey, CachedResponse> entry = iterator.next();
104+
if (entry.getValue().isStale(accessTime, this.timeToLive)) {
105+
iterator.remove();
106+
}
107+
}
108+
}
109+
catch (Exception ex) {
110+
}
111+
}
112+
92113
private boolean hasInput(InvocationContext context) {
93114
Map<String, Object> arguments = context.getArguments();
94115
if (!ObjectUtils.isEmpty(arguments)) {

spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2020 the original author or authors.
2+
* Copyright 2012-2021 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@
2323
import java.util.Map;
2424
import java.util.concurrent.atomic.AtomicInteger;
2525

26+
import org.assertj.core.api.InstanceOfAssertFactories;
2627
import org.junit.jupiter.api.Test;
2728
import reactor.core.publisher.Flux;
2829
import reactor.core.publisher.Mono;
@@ -101,6 +102,31 @@ void cacheInTtlWithFluxResponse() {
101102
assertThat(response).isSameAs(cachedResponse);
102103
}
103104

105+
@Test // gh-28313
106+
void cacheWhenEachPrincipalIsUniqueDoesNotConsumeTooMuchMemory() throws Exception {
107+
MonoOperationInvoker target = new MonoOperationInvoker();
108+
CachingOperationInvoker invoker = new CachingOperationInvoker(target, 50L);
109+
int count = 1000;
110+
for (int i = 0; i < count; i++) {
111+
invokeWithUniquePrincipal(invoker);
112+
}
113+
long expired = System.currentTimeMillis() + 50;
114+
while (System.currentTimeMillis() < expired) {
115+
Thread.sleep(10);
116+
}
117+
invokeWithUniquePrincipal(invoker);
118+
assertThat(invoker).extracting("cachedResponses").asInstanceOf(InstanceOfAssertFactories.MAP)
119+
.hasSizeLessThan(count);
120+
}
121+
122+
private void invokeWithUniquePrincipal(CachingOperationInvoker invoker) {
123+
SecurityContext securityContext = mock(SecurityContext.class);
124+
Principal principal = mock(Principal.class);
125+
given(securityContext.getPrincipal()).willReturn(principal);
126+
InvocationContext context = new InvocationContext(securityContext, Collections.emptyMap());
127+
((Mono<?>) invoker.invoke(context)).block();
128+
}
129+
104130
private void assertCacheIsUsed(Map<String, Object> parameters) {
105131
assertCacheIsUsed(parameters, null);
106132
}

0 commit comments

Comments
 (0)