4545import io .grpc .xds .MetadataRegistry .MetadataValueParser ;
4646import io .grpc .xds .XdsConfig .XdsClusterConfig ;
4747import io .grpc .xds .client .XdsResourceType .ResourceInvalidException ;
48- import java .util .Iterator ;
48+ import java .util .ArrayList ;
4949import java .util .LinkedHashMap ;
50+ import java .util .List ;
5051import java .util .Map ;
5152import java .util .Map .Entry ;
5253import java .util .concurrent .ScheduledExecutorService ;
@@ -133,7 +134,9 @@ public ClientInterceptor buildClientInterceptor(FilterConfig config,
133134 @ Nullable FilterConfig overrideConfig , ScheduledExecutorService scheduler ) {
134135
135136 ComputeEngineCredentials credentials = ComputeEngineCredentials .create ();
136- callCredentialsCache .resizeCache (((GcpAuthenticationConfig ) config ).getCacheSize ());
137+ synchronized (callCredentialsCache ) {
138+ callCredentialsCache .resizeCache (((GcpAuthenticationConfig ) config ).getCacheSize ());
139+ }
137140 return new ClientInterceptor () {
138141 @ Override
139142 public <ReqT , RespT > ClientCall <ReqT , RespT > interceptCall (
@@ -259,7 +262,7 @@ public void sendMessage(ReqT message) {}
259262
260263 private static final class LruCache <K , V > {
261264
262- private final Map <K , V > cache ;
265+ private Map <K , V > cache ;
263266 private int maxSize ;
264267
265268 LruCache (int maxSize ) {
@@ -270,7 +273,7 @@ private static final class LruCache<K, V> {
270273 true ) {
271274 @ Override
272275 protected boolean removeEldestEntry (Map .Entry <K , V > eldest ) {
273- return size () > maxSize ;
276+ return size () > LruCache . this . maxSize ;
274277 }
275278 };
276279 }
@@ -280,15 +283,19 @@ V getOrInsert(K key, Function<K, V> create) {
280283 }
281284
282285 private void resizeCache (int newSize ) {
283- while (cache .size () > newSize ) {
284- Iterator <Entry <K , V >> iterator = cache .entrySet ().iterator ();
285- if (iterator .hasNext ()) {
286- iterator .next ();
287- iterator .remove ();
288- } else {
289- break ;
290- }
286+ if (newSize >= maxSize ) {
287+ maxSize = newSize ;
288+ return ;
289+ }
290+ LinkedHashMap <K , V > newCache = new LinkedHashMap <>(newSize , 0.75f , true );
291+ // Copy the MRU entries (which are at the end of access-order map)
292+ List <Entry <K , V >> entries = new ArrayList <>(cache .entrySet ());
293+ int start = Math .max (0 , entries .size () - newSize );
294+ for (int i = entries .size () - 1 ; i >= start ; i --) {
295+ Map .Entry <K , V > entry = entries .get (i );
296+ newCache .put (entry .getKey (), entry .getValue ());
291297 }
298+ cache = newCache ;
292299 maxSize = newSize ;
293300 }
294301 }
0 commit comments