summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/util/GenericDataCache.java
blob: a7116b790a61768660de2bd88b0d6c663e134a51 (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package org.openslx.util;

import java.util.concurrent.atomic.AtomicReference;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public abstract class GenericDataCache<T>
{

	private static final Logger LOGGER = LogManager.getLogger( GenericDataCache.class );

	/**
	 * How long the cached data is valid after fetching
	 */
	private final int validMs;

	/**
	 * Deadline when the cache goes invalid
	 */
	private long validUntil = 0;

	/**
	 * The data being held
	 */
	private final AtomicReference<T> item = new AtomicReference<>();

	public GenericDataCache( int validMs )
	{
		this.validMs = validMs;
	}

	/**
	 * Get the cached object, but refresh the cache first if
	 * the cached instance is too old.
	 * 
	 * @return
	 */
	public T get()
	{
		return get( CacheMode.DEFAULT );
	}

	/**
	 * Get the cached object, using the given cache access strategy.
	 * ALWAYS_CACHED: Never refresh the cache, except if it has never been fetched before
	 * DEFAULT: Only fetch from remote if the cached value is too old
	 * NEVER_CACHED: Always fetch from remote. If it fails, return null
	 * 
	 * @param mode Cache access strategy as described above
	 * @return T
	 */
	public T get( CacheMode mode )
	{
		switch ( mode ) {
		case FORCE_CACHED:
			break;
		case PREFER_CACHED:
			if ( validUntil == 0 )
				ensureUpToDate( true );
			break;
		case DEFAULT:
			ensureUpToDate( false );
			break;
		case NEVER_CACHED:
			if ( !ensureUpToDate( true ) )
				return null;
			break;
		}
		return item.get();
	}

	private synchronized boolean ensureUpToDate( boolean force )
	{
		final long now = System.currentTimeMillis();
		if ( !force && now < validUntil )
			return true;
		T fetched;
		try {
			fetched = update();
			if ( fetched == null )
				return false;
		} catch ( Exception e ) {
			LOGGER.warn( "Could not fetch fresh data", e );
			return false;
		}
		item.set( fetched );
		validUntil = now + validMs;
		return true;
	}

	protected abstract T update() throws Exception;

	//

	public static enum CacheMode
	{
		/**
		 * Use cache, even if the item has never been fetched before.
		 */
		FORCE_CACHED,
		/**
		 * Use cache if it's not empty, no matter how old it is.
		 */
		PREFER_CACHED,
		/**
		 * Obey the cache timeout value of this cache.
		 */
		DEFAULT,
		/**
		 * Always fetch a fresh instance of the item.
		 */
		NEVER_CACHED
	}

}