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
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2020 the original author or authors.
|
||||
* Copyright 2012-2021 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -23,6 +23,7 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.assertj.core.api.InstanceOfAssertFactories;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -101,6 +102,31 @@ class CachingOperationInvokerTests {
|
||||
assertThat(response).isSameAs(cachedResponse);
|
||||
}
|
||||
|
||||
@Test // gh-28313
|
||||
void cacheWhenEachPrincipalIsUniqueDoesNotConsumeTooMuchMemory() throws Exception {
|
||||
MonoOperationInvoker target = new MonoOperationInvoker();
|
||||
CachingOperationInvoker invoker = new CachingOperationInvoker(target, 50L);
|
||||
int count = 1000;
|
||||
for (int i = 0; i < count; i++) {
|
||||
invokeWithUniquePrincipal(invoker);
|
||||
}
|
||||
long expired = System.currentTimeMillis() + 50;
|
||||
while (System.currentTimeMillis() < expired) {
|
||||
Thread.sleep(10);
|
||||
}
|
||||
invokeWithUniquePrincipal(invoker);
|
||||
assertThat(invoker).extracting("cachedResponses").asInstanceOf(InstanceOfAssertFactories.MAP)
|
||||
.hasSizeLessThan(count);
|
||||
}
|
||||
|
||||
private void invokeWithUniquePrincipal(CachingOperationInvoker invoker) {
|
||||
SecurityContext securityContext = mock(SecurityContext.class);
|
||||
Principal principal = mock(Principal.class);
|
||||
given(securityContext.getPrincipal()).willReturn(principal);
|
||||
InvocationContext context = new InvocationContext(securityContext, Collections.emptyMap());
|
||||
((Mono<?>) invoker.invoke(context)).block();
|
||||
}
|
||||
|
||||
private void assertCacheIsUsed(Map<String, Object> parameters) {
|
||||
assertCacheIsUsed(parameters, null);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user