blob: b4ca77f6aae28858b68682bdf18e4e8ac83f92aa (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package org.openslx.bwlp.sat.thrift.cache;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
/**
* Class that caches an instance of a given class for 10 minutes.
* If the cache expired and a fresh instance cannot be acquired,
* the old instance will be returned.
*
* @param <T> The class to cache
*/
public abstract class CacheBase<T> {
private static final Logger LOGGER = Logger.getLogger(CacheBase.class);
private static final int TIMEOUT = 10 * 60 * 1000;
private T cachedInstance = null;
private long cacheTimeout = 0;
protected abstract T getCallback() throws TException;
protected synchronized T getInternal() {
final long now = System.currentTimeMillis();
if (cachedInstance == null || now > cacheTimeout) {
try {
T freshInstance = getCallback();
if (freshInstance != null) {
cachedInstance = freshInstance;
cacheTimeout = now + TIMEOUT;
}
} catch (TException e) {
LOGGER.warn("Could not retrieve fresh instance of " + getClass().getSimpleName(), e);
}
}
return cachedInstance;
}
}
|