01: /*
02: * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright
03: * notice. All rights reserved.
04: */
05: package com.tc.util.sequence;
06:
07: import EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap;
08:
09: public class SequenceGenerator {
10:
11: public static class SequenceGeneratorException extends Exception {
12:
13: public SequenceGeneratorException(Exception e) {
14: super (e);
15: }
16:
17: }
18:
19: public interface SequenceGeneratorListener {
20:
21: public void sequenceCreatedFor(Object key)
22: throws SequenceGeneratorException;
23:
24: public void sequenceDestroyedFor(Object key);
25:
26: }
27:
28: private final ConcurrentReaderHashMap map = new ConcurrentReaderHashMap();
29: private final SequenceGeneratorListener listener;
30:
31: public SequenceGenerator() {
32: this (null);
33: }
34:
35: public SequenceGenerator(SequenceGeneratorListener listener) {
36: this .listener = listener;
37: }
38:
39: public long getNextSequence(Object key)
40: throws SequenceGeneratorException {
41: Sequence seq = (Sequence) map.get(key);
42: if (seq != null)
43: return seq.next();
44: synchronized (map) {
45: if (!map.containsKey(key)) {
46: if (listener != null)
47: listener.sequenceCreatedFor(key);
48: map.put(key, (seq = new SimpleSequence()));
49: } else {
50: seq = (Sequence) map.get(key);
51: }
52: }
53: return seq.next();
54: }
55:
56: public void clearSequenceFor(Object key) {
57: if (map.remove(key) != null && listener != null) {
58: listener.sequenceDestroyedFor(key);
59: }
60: }
61:
62: }
|