2424package org .incendo .cloud ;
2525
2626import io .leangen .geantyref .TypeToken ;
27- import java .util .ArrayDeque ;
2827import java .util .Collection ;
2928import java .util .Collections ;
30- import java .util .Deque ;
3129import java .util .HashMap ;
3230import java .util .HashSet ;
3331import java .util .LinkedList ;
3432import java .util .List ;
3533import java .util .Map ;
3634import java .util .Objects ;
3735import java .util .Set ;
38- import java .util .concurrent .ConcurrentHashMap ;
36+ import java .util .concurrent .atomic . AtomicInteger ;
3937import java .util .concurrent .atomic .AtomicReference ;
4038import java .util .function .Consumer ;
4139import java .util .function .Function ;
@@ -384,8 +382,8 @@ public boolean hasCapability(final @NonNull CloudCapability capability) {
384382 return Collections .unmodifiableSet (new HashSet <>(this .capabilities ));
385383 }
386384
387- private final ThreadLocal <Deque <Map <Pair <C , Permission >, PermissionResult >>> threadLocalPermissionCache =
388- ThreadLocal .withInitial (ArrayDeque :: new );
385+ private final ThreadLocal <Pair <Map <Pair <C , Permission >, PermissionResult >, AtomicInteger >> threadLocalPermissionCache =
386+ ThreadLocal .withInitial (() -> Pair . of ( new HashMap <>(), new AtomicInteger ( 0 )) );
389387
390388 @ SuppressWarnings ("rawtypes" )
391389 private @ NonNull <T > PermissionResult testPermissionCaching (
@@ -396,7 +394,7 @@ public boolean hasCapability(final @NonNull CloudCapability capability) {
396394 if (!this .settings .get (ManagerSetting .REDUCE_REDUNDANT_PERMISSION_CHECKS )) {
397395 return tester .apply (Pair .of (sender , permission ));
398396 }
399- return Objects . requireNonNull ( this .threadLocalPermissionCache .get ().peek () )
397+ return this .threadLocalPermissionCache .get ().first ( )
400398 .computeIfAbsent ((Pair ) Pair .of (sender , permission ), (Function ) tester );
401399 }
402400
@@ -413,10 +411,13 @@ public boolean hasCapability(final @NonNull CloudCapability capability) {
413411 final @ NonNull Permission permission
414412 ) {
415413 try {
416- this .threadLocalPermissionCache .get ().push ( new HashMap <>() );
414+ this .threadLocalPermissionCache .get ().second (). incrementAndGet ( );
417415 return this .testPermission_ (sender , permission );
418416 } finally {
419- this .threadLocalPermissionCache .get ().pop ();
417+ final Pair <Map <Pair <C , Permission >, PermissionResult >, AtomicInteger > pair = this .threadLocalPermissionCache .get ();
418+ if (pair .second ().getAndDecrement () == 1 ) {
419+ pair .first ().clear ();
420+ }
420421 }
421422 }
422423
0 commit comments