How do I know if a given string is already in the Java string pool?

Is there any method or method how to find out if a given String s already in the string pool? How and when is a Java String pool created? What contains the original elements?

+6
source share
3 answers

I answer: there is no general solution. What you can do is:

 boolean wasAlreadyInterned = str.intern() == str; 

but it has a side effect that it is now interned for sure.

JavaDoc String#intern says that the String class privately supports a string pool that is initially empty.

If you look at the implementation of the String class, all you see is

 public native String intern(); 

The Java Language Specification, chapter 3.10.5, string literals says:

string literals - or, more generally, strings that are constant expression values ​​(Β§15.28) - are β€œinterned” to instances using the String.intern method.

+4
source

The question does not have a good answer.

The string pool used by String.intern is based on a weak map, and there is no way to synchronize the user code on this map, so any answer you receive may not be acceptable before you can use it.

Even string literals can disappear from the inner pool. Class unloading can cause string literals to become unavailable, and since loading classes depends on the GC, this is unpredictable.

I repeat, very little useful information can be obtained by analyzing the internal pool, with the exception of the total amount of memory, and JVMs, as a rule, have more efficient ways to access them through their logging and debugging.

+4
source

I think you need to look like pulling rows from a pool

-1
source

Source: https://habr.com/ru/post/943989/


All Articles