1919
2020package com .sk89q .worldguard .session ;
2121
22+ import com .google .common .cache .Cache ;
2223import com .google .common .cache .CacheBuilder ;
2324import com .google .common .cache .CacheLoader ;
2425import com .google .common .cache .LoadingCache ;
@@ -67,10 +68,9 @@ public abstract class AbstractSessionManager implements SessionManager {
6768 .expireAfterWrite (2 , TimeUnit .SECONDS )
6869 .build (CacheLoader .from (tuple -> BYPASS_PERMISSION_TEST .test (tuple .getWorld (), tuple .getPlayer ())));
6970
70- private final LoadingCache <CacheKey , Session > sessions = CacheBuilder .newBuilder ()
71+ private final Cache <CacheKey , Session > sessions = CacheBuilder .newBuilder ()
7172 .expireAfterAccess (SESSION_LIFETIME , TimeUnit .MINUTES )
72- .build (CacheLoader .from (key ->
73- createSession (key .playerRef .get ())));
73+ .build ();
7474
7575 private boolean hasCustom = false ;
7676 private List <Handler .Factory <? extends Handler >> handlers = new LinkedList <>();
@@ -152,7 +152,7 @@ public boolean hasBypass(LocalPlayer player, World world) {
152152 @ Override
153153 public void resetState (LocalPlayer player ) {
154154 checkNotNull (player , "player" );
155- @ Nullable Session session = sessions . getIfPresent (new CacheKey (player ));
155+ @ Nullable Session session = getIfPresentInternal (new CacheKey (player ));
156156 if (session != null ) {
157157 session .resetState (player );
158158 }
@@ -161,22 +161,35 @@ public void resetState(LocalPlayer player) {
161161 @ Override
162162 @ Nullable
163163 public Session getIfPresent (LocalPlayer player ) {
164- return sessions .getIfPresent (new CacheKey (player ));
164+ return getIfPresentInternal (new CacheKey (player ));
165+ }
166+
167+ private Session getIfPresentInternal (CacheKey cacheKey ) {
168+ @ Nullable Session session = sessions .getIfPresent (cacheKey );
169+ if (session != null ) {
170+ session .ensureInitialized (cacheKey .playerRef .get (), this ::initializeSession );
171+ return session ;
172+ }
173+ return null ;
165174 }
166175
167176 @ Override
168177 public Session get (LocalPlayer player ) {
169- return sessions .getUnchecked (new CacheKey (player ));
178+ Session session = sessions .asMap ().computeIfAbsent (new CacheKey (player ), (k ) -> new Session (this ));
179+ session .ensureInitialized (player , this ::initializeSession );
180+ return session ;
170181 }
171182
172183 @ Override
173184 public Session createSession (LocalPlayer player ) {
174- Session session = new Session (this );
185+ return get (player );
186+ }
187+
188+ private void initializeSession (Session session , LocalPlayer player ) {
175189 for (Handler .Factory <? extends Handler > factory : handlers ) {
176190 session .register (factory .create (session ));
177191 }
178192 session .initialize (player );
179- return session ;
180193 }
181194
182195 protected static final class CacheKey {
0 commit comments