This repository has been archived on 2021-09-09. You can view files and clone it, but cannot push or open issues or pull requests.
geoportal-service/src/main/java/org/gcube/application/geoportal/service/engine/providers/AbstractScopedMap.java

68 lines
2.0 KiB
Java
Raw Normal View History

2021-08-04 16:22:29 +02:00
package org.gcube.application.geoportal.service.engine.providers;
2020-11-19 17:38:56 +01:00
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;
2020-11-19 17:38:56 +01:00
@Slf4j
@RequiredArgsConstructor
public abstract class AbstractScopedMap<T> implements Engine<T>{
// scope-> object
2021-08-04 16:22:29 +02:00
private ConcurrentHashMap<String, TTLObject<T>> scopeMap=new ConcurrentHashMap<String,TTLObject<T>>();
2020-11-19 17:38:56 +01:00
@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);
2021-09-07 10:30:27 +02:00
2020-11-19 18:50:20 +01:00
TTLObject<T> found=scopeMap.get(currentScope);
2021-09-07 10:30:27 +02:00
if(found== null){
log.debug(name+" : init object for context "+currentScope);
2021-09-07 11:28:11 +02:00
TTLObject<T> toPut=new TTLObject<T>(LocalDateTime.now(),retrieveObject());
scopeMap.put(currentScope, toPut);
return toPut.getTheObject();
2021-09-07 10:30:27 +02:00
}
2020-11-19 17:38:56 +01:00
if(TTL!=null) {
if(!found.getCreationTime().plus(TTL).isBefore(LocalDateTime.now())) {
log.debug(name+" : elapsed TTL, disposing..");
dispose(found.getTheObject());
found=scopeMap.put(currentScope, new TTLObject<T>(LocalDateTime.now(),retrieveObject()));
}
2021-09-07 10:30:27 +02:00
}else {log.debug(name+" : TTL is null, never disposing..");}
2020-11-19 17:38:56 +01:00
return found.getTheObject();
}
@Override
public void shustdown() {
log.warn(name + ": shutting down");
scopeMap.forEach((String s,TTLObject<T> o)->{
2020-11-19 18:50:20 +01:00
try{if(o!=null&&o.getTheObject()!=null)
dispose(o.getTheObject());
}catch(Throwable t) {
log.warn(name +": unable to dispose ",t);
}
2020-11-19 17:38:56 +01:00
});
}
protected abstract T retrieveObject() throws ConfigurationException;
protected abstract void dispose(T toDispose);
}