1 package org.apache.lucene.util;
3 * Licensed to the Apache Software Foundation (ASF) under one or more
4 * contributor license agreements. See the NOTICE file distributed with
5 * this work for additional information regarding copyright ownership.
6 * The ASF licenses this file to You under the Apache License, Version 2.0
7 * (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
21 * Simple lockless and memory barrier free String intern cache that is guaranteed
22 * to return the same String instance as String.intern()
27 public class SimpleStringInterner extends StringInterner {
29 private static class Entry {
30 final private String str;
31 final private int hash;
33 private Entry(String str, int hash, Entry next) {
40 private final Entry[] cache;
41 private final int maxChainLength;
44 * @param tableSize Size of the hash table, should be a power of two.
45 * @param maxChainLength Maximum length of each bucket, after which the oldest item inserted is dropped.
47 public SimpleStringInterner(int tableSize, int maxChainLength) {
48 cache = new Entry[Math.max(1,BitUtil.nextHighestPowerOfTwo(tableSize))];
49 this.maxChainLength = Math.max(2,maxChainLength);
53 public String intern(String s) {
55 // In the future, it may be worth augmenting the string hash
56 // if the lower bits need better distribution.
57 int slot = h & (cache.length-1);
59 Entry first = this.cache[slot];
60 Entry nextToLast = null;
64 for(Entry e=first; e!=null; e=e.next) {
65 if (e.hash == h && (e.str == s || e.str.compareTo(s)==0)) {
66 // if (e.str == s || (e.hash == h && e.str.compareTo(s)==0)) {
76 // insertion-order cache: add new entry at head
78 this.cache[slot] = new Entry(s, h, first);
79 if (chainLength >= maxChainLength) {
81 nextToLast.next = null;