gcube-cms-suite/geoportal-service/src/main/java/org/gcube/application/geoportal/service/engine/providers/AbstractScopedMap.java

71 lines
2.1 KiB
Java
Raw Normal View History

2021-09-20 16:47:35 +02:00
package org.gcube.application.geoportal.service.engine.providers;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.gcube.application.geoportal.service.model.internal.faults.ConfigurationException;
import org.gcube.application.geoportal.service.utils.ContextUtils;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAmount;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@RequiredArgsConstructor
public abstract class AbstractScopedMap<T> implements Engine<T>{
// scope-> object
private ConcurrentHashMap<String, TTLObject<T>> scopeMap=new ConcurrentHashMap<String,TTLObject<T>>();
@Setter
private TemporalAmount TTL=null;
@NonNull
private String name;
@Synchronized
public T getObject() throws ConfigurationException {
String currentScope=ContextUtils.getCurrentScope();
log.debug(name+" : obtaining object for context "+currentScope);
TTLObject<T> found=scopeMap.get(currentScope);
if(found== null){
log.debug(name+" : init object for context "+currentScope);
TTLObject<T> toPut=new TTLObject<T>(LocalDateTime.now(),retrieveObject());
scopeMap.put(currentScope, toPut);
return toPut.getTheObject();
}
if(TTL!=null) {
2021-10-05 16:27:19 +02:00
if(found.getCreationTime().plus(TTL).isBefore(LocalDateTime.now())) {
2021-09-20 16:47:35 +02:00
log.debug(name+" : elapsed TTL, disposing..");
dispose(found.getTheObject());
2021-10-05 16:27:19 +02:00
TTLObject<T> newer=new TTLObject<T>(LocalDateTime.now(),retrieveObject());
scopeMap.put(currentScope, newer);
found=scopeMap.get(currentScope);
2021-09-20 16:47:35 +02:00
}
}else {log.debug(name+" : TTL is null, never disposing..");}
2021-10-05 16:27:19 +02:00
log.debug("Returning {} ",found);
2021-09-20 16:47:35 +02:00
return found.getTheObject();
}
@Override
2021-10-05 16:27:19 +02:00
public void shutdown() {
2021-09-20 16:47:35 +02:00
log.warn(name + ": shutting down");
scopeMap.forEach((String s,TTLObject<T> o)->{
try{if(o!=null&&o.getTheObject()!=null)
dispose(o.getTheObject());
}catch(Throwable t) {
log.warn(name +": unable to dispose ",t);
}
});
}
protected abstract T retrieveObject() throws ConfigurationException;
protected abstract void dispose(T toDispose);
}