summaryrefslogtreecommitdiffstats
path: root/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/thrift/cache/CacheBase.java
blob: 1efc72d448757b269f92f9943e0725cd04750c03 (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
42
package org.openslx.bwlp.sat.thrift.cache;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.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 = LogManager.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;
	}

}