public class StringInterner extends Object
StringInterner only guarantees it will behave in a correct manner. When you ask it for a String for a given input, it must return a String which matches the toString() of that CharSequence.
It doesn't guarantee that all threads see the same data, nor that multiple threads will return the same String object for the same string. It is designed to be a best-effort basis so it can be as lightweight as possible.
So while technically not thread safe, it doesn't prevent it operating correctly when used from multiple threads, but it is faster than added explicit locking or thread safety. NOTE: It does rely on String being thread safe, something which was guaranteed from Java 5.0 onwards c.f. JSR 133.
Discussion ...
This class provides string interning functionality. It's used to optimize memory usage by caching strings and referring to them by index, rather than storing duplicate strings. When you 'intern' a string, it's looked up in the cache and if an equal string is found, it's returned instead of creating a new one.
| Modifier and Type | Class and Description |
|---|---|
static interface |
StringInterner.Changed
Callback for receiving notification when a value is stored.
|
| Modifier and Type | Field and Description |
|---|---|
protected String[] |
interner |
protected int |
mask |
protected int |
shift |
protected boolean |
toggle |
| Constructor and Description |
|---|
StringInterner(int capacity)
Constructs a new StringInterner with the specified capacity.
|
| Modifier and Type | Method and Description |
|---|---|
int |
capacity() |
@Nullable String |
get(int index)
Returns the interned string held at the given index.
|
int |
index(@Nullable CharSequence cs,
@Nullable StringInterner.Changed onChanged)
Returns the slot index for the given text, adding it if absent.
|
@Nullable String |
intern(@Nullable CharSequence cs)
Interns the specified CharSequence.
|
protected boolean |
toggle() |
int |
valueCount()
Returns the number of values in the interner.
|
protected final String[] interner
protected final int mask
protected final int shift
protected boolean toggle
public StringInterner(int capacity)
throws IllegalArgumentException
capacity - the initial capacity of the interner.IllegalArgumentException - if the capacity is invalid.public int capacity()
@Nullable public @Nullable String intern(@Nullable @Nullable CharSequence cs)
cs - the CharSequence to intern.public int index(@Nullable
@Nullable CharSequence cs,
@Nullable
@Nullable StringInterner.Changed onChanged)
cs - the source textonChanged - callback invoked when a new value is stored-1 if the text is too long@Nullable public @Nullable String get(int index)
index - the slot obtained from index(CharSequence, Changed)null if no value is stored at that indexprotected boolean toggle()
public int valueCount()
Copyright © 2026 Chronicle Software Ltd. All rights reserved.