01: package ri.cache;
02:
03: import ri.cache.util.CacheListenerSupport;
04:
05: import javax.cache.Cache;
06: import javax.cache.CacheListener;
07: import javax.cache.CacheManager;
08: import java.util.AbstractMap;
09: import java.util.EnumSet;
10: import java.util.concurrent.atomic.AtomicReference;
11:
12: /**
13: * AbstractCache
14: *
15: * @author Brian Goetz
16: */
17: public abstract class AbstractCache<K, V> extends AbstractMap<K, V>
18: implements Cache<K, V> {
19: protected final CacheListenerSupport<K, V> listeners = new CacheListenerSupport<K, V>();
20: protected final String name;
21: protected final AtomicReference<State> state = new AtomicReference<State>(
22: State.STARTING);
23: protected final EnumSet<State> RUNNING_OR_STARTING = EnumSet.of(
24: State.RUNNING, State.STARTING);
25: protected final EnumSet<State> RUNNING_OR_STOPPING = EnumSet.of(
26: State.RUNNING, State.STOPPING);
27:
28: protected CacheManager cacheManager;
29:
30: protected AbstractCache(String name) {
31: this .name = name;
32: }
33:
34: public CacheManager getCacheManager() {
35: return cacheManager;
36: }
37:
38: public void setCacheManager(CacheManager cacheManager) {
39: this .cacheManager = cacheManager;
40: }
41:
42: public void addListener(CacheListener<K, V> listener) {
43: requireState(State.RUNNING);
44: listeners.addListener(listener);
45: }
46:
47: public void removeListener(CacheListener<K, V> listener) {
48: requireState(State.RUNNING);
49: listeners.removeListener(listener);
50: }
51:
52: public String getName() {
53: return name;
54: }
55:
56: public State getState() {
57: return state.get();
58: }
59:
60: protected void transitionState(State fromState, State toState) {
61: if (!state.compareAndSet(fromState, toState))
62: throw new IllegalStateException("Expecting cache " + name
63: + " to be in state " + fromState + ", found state "
64: + state.get());
65: }
66:
67: protected void requireState(State requiredState) {
68: State curState = state.get();
69: if (curState != requiredState)
70: throw new IllegalStateException("Expecting cache " + name
71: + " to be in state " + requiredState
72: + ", found state " + curState);
73: }
74:
75: protected void requireState(EnumSet<State> requiredStates) {
76: State curState = state.get();
77: if (!requiredStates.contains(curState))
78: throw new IllegalStateException("Expecting cache " + name
79: + " to be in states " + requiredStates
80: + ", found state " + curState);
81: }
82: }
|