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 https://stackoverflow.com/questions/63383745/string-array-needless-synchronization/63383983
Modifier and Type | Class and Description |
---|---|
static interface |
StringInterner.Changed |
Modifier and Type | Field and Description |
---|---|
protected String[] |
interner |
protected int |
mask |
protected int |
shift |
protected boolean |
toggle |
Constructor and Description |
---|
StringInterner(int capacity) |
Modifier and Type | Method and Description |
---|---|
int |
capacity() |
String |
get(int index)
get an intered string based on the index
|
int |
index(@Nullable CharSequence cs,
@Nullable StringInterner.Changed onChanged)
provide
|
@Nullable String |
intern(@Nullable CharSequence cs) |
protected boolean |
toggle() |
int |
valueCount() |
protected final String[] interner
protected final int mask
protected final int shift
protected boolean toggle
public StringInterner(int capacity) throws IllegalArgumentException
IllegalArgumentException
public int capacity()
@Nullable public @Nullable String intern(@Nullable @Nullable CharSequence cs)
public int index(@Nullable @Nullable CharSequence cs, @Nullable @Nullable StringInterner.Changed onChanged)
cs
- a source string
An example of the StringInterner used in conjunction with the uppercase[] to cache another value
private String[] uppercase; public void myMethod() throws IllegalArgumentException { StringInterner si = new StringInterner(128); uppercase = new String[si.capacity()]; String lowerCaseString = ... int index = si.index(lowerCaseString, this::changed); if (index != -1) assertEquals(lowerCaseString.toUpperCase(), uppercase[index]); } private void changed(int index, String value) { uppercase[index] = value.toUpperCase(); }
public String get(int index)
index
- the index of the interner string, to acquire an index call index(java.lang.CharSequence, net.openhft.chronicle.core.pool.StringInterner.Changed)
protected boolean toggle()
public int valueCount()
Copyright © 2023. All rights reserved.