KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > objectserver > persistence > impl > StringIndexImpl


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.objectserver.persistence.impl;
5
6 import com.tc.io.serializer.api.StringIndex;
7 import com.tc.objectserver.persistence.api.StringIndexPersistor;
8
9 import gnu.trove.TLongObjectHashMap;
10 import gnu.trove.TLongObjectIterator;
11 import gnu.trove.TObjectLongHashMap;
12
13 public class StringIndexImpl implements StringIndex {
14   private static final int NULL = 0;
15   private final StringIndexPersistor persistor;
16   private final TLongObjectHashMap indexToString;
17   private final TObjectLongHashMap stringToIndex;
18   private long counter;
19
20   public StringIndexImpl(StringIndexPersistor persistor) {
21     this(persistor, 10);
22   }
23
24   public StringIndexImpl(StringIndexPersistor persistor, int initialCapacity) {
25     this.persistor = persistor;
26
27     this.indexToString = new TLongObjectHashMap(initialCapacity);
28     this.stringToIndex = new TObjectLongHashMap(initialCapacity);
29
30     for (TLongObjectIterator i = persistor.loadMappingsInto(indexToString).iterator(); i.hasNext();) {
31       i.advance();
32       long index = i.key();
33       if (index > counter) counter = index;
34       this.stringToIndex.put(i.value(), index);
35     }
36   }
37
38   public synchronized long getOrCreateIndexFor(String JavaDoc string) {
39     if (string == null) return NULL;
40     long rv = stringToIndex.get(string);
41     if (rv < 1) {
42       rv = ++counter;
43       indexToString.put(rv, string);
44       stringToIndex.put(string, rv);
45       persistor.saveMapping(rv, string);
46     }
47     return rv;
48   }
49
50   public synchronized String JavaDoc getStringFor(long index) {
51     if (index == NULL) return null;
52     String JavaDoc rv = (String JavaDoc) indexToString.get(index);
53     if (rv == null) throw new AssertionError JavaDoc("Unknown index: " + index);
54     return rv;
55   }
56
57   public synchronized String JavaDoc toString() {
58     StringBuffer JavaDoc rv = new StringBuffer JavaDoc();
59     rv.append("[");
60     for (TLongObjectIterator i = indexToString.iterator(); i.hasNext();) {
61       i.advance();
62       rv.append(i.key() + "=>" + i.value());
63       if (i.hasNext()) rv.append(", ");
64     }
65     rv.append("]");
66     return rv.toString();
67   }
68   
69   // For Testing
70
public TObjectLongHashMap getString2LongMappings() {
71     return stringToIndex;
72   }
73
74 }
75
Popular Tags