Improved code

This commit is contained in:
Luca Frosini 2024-11-12 17:03:56 +01:00
parent 18b77a179a
commit 96b10b3b1d
1 changed files with 13 additions and 6 deletions

View File

@ -62,9 +62,12 @@ public class ContextCache {
protected Map<String, UUID> contextFullNameToUUID;
protected Tree<Context> contextsTree;
protected boolean initialized;
public ContextCache() {
Calendar now = Calendar.getInstance();
cleanCache(now);
initialized = false;
}
public void cleanCache() {
@ -72,7 +75,7 @@ public class ContextCache {
}
protected void cleanCache(Calendar calendar) {
this.contexts = null;
this.contexts = new ArrayList<>();
this.uuidToContext = new LinkedHashMap<>();
this.uuidToContextFullName = new LinkedHashMap<>();
this.contextFullNameToUUID = new TreeMap<>();
@ -84,6 +87,7 @@ public class ContextCache {
this.expiringTime.setTimeInMillis(calendar.getTimeInMillis());
this.expiringTime.add(Calendar.MILLISECOND, -1);
this.expiringTime.add(Calendar.MILLISECOND, expiringTimeout);
initialized = false;
}
public void renew() throws ResourceRegistryException {
@ -103,14 +107,17 @@ public class ContextCache {
public synchronized void refreshContextsIfNeeded() throws ResourceRegistryException {
Calendar now = Calendar.getInstance();
if((now.after(expiringTime) || (contexts==null)) && contextCacheRenewal!=null) {
if((now.after(expiringTime) || (!initialized)) && contextCacheRenewal!=null) {
try {
List<Context> contexts = contextCacheRenewal.renew();
setContexts(now, contexts);
initialized = true;
} catch (ResourceRegistryException e) {
logger.error("Unable to refresh Cache", e);
if(contexts==null) {
if(!initialized) {
logger.error("Unable to initialize Context Cache", e);
throw e;
}else {
logger.error("Unable to refresh Context Cache", e);
}
}
@ -129,7 +136,6 @@ public class ContextCache {
protected void setContexts(Calendar calendar, List<Context> contexts) {
cleanCache(calendar);
this.contexts = new ArrayList<>();
for(Context c : contexts) {
UUID uuid = c.getID();
@ -232,7 +238,8 @@ public class ContextCache {
return new TreeMap<>(contextFullNameToUUID);
}
public Tree<Context> getContextsTree() {
public Tree<Context> getContextsTree() throws ResourceRegistryException {
refreshContextsIfNeeded();
return contextsTree;
}