Is there any method or technique how to know that given String s
is already in the String pool? How and when is Java String
pool creating? What does initial members it contain?

- 1,613
- 4
- 17
- 24
-
By "string pool", do you mean the one used by `String.intern`? – Mike Samuel Apr 30 '13 at 18:36
-
1All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification. – jlordo Apr 30 '13 at 18:37
-
1@ArtyMathJava: what's the real problem you are trying to solve? – jlordo Apr 30 '13 at 18:42
-
@jlordo if I'm not mistaken not only. Also signatures of methods and other stuff are there. – angry_gopher Apr 30 '13 at 18:43
-
@jlordo, given String s, is it in the pool? – angry_gopher Apr 30 '13 at 18:44
-
4@ArtyMathJava: yes, you asked that. **Why** do you want to know this? – jlordo Apr 30 '13 at 18:45
-
2@jlordo it's just my curiosity. – angry_gopher Apr 30 '13 at 18:48
-
2jlordo is asking a good question, because knowing why you have this immediate problem might help us steer you away from a brittle half-solution towards a real solution to your underlying problem. – Mike Samuel Apr 30 '13 at 18:48
-
@Mike Samuel, thanks. It is only theorethical question. Maybe, there is no practical part. – angry_gopher Apr 30 '13 at 18:50
3 Answers
The question has no good answer.
The string pool used by String.intern
is based on a weak map and there is no way for user code to synchronize on that map, so any answer you get might be invalid before you can use it.
Even string literals can disappear from the intern pool. Class unloading can result in string literals becoming unreachable and since class-loading depends on the GC it is unpredictable.
To reiterate, very little useful information can come from analyzing the intern pool except for its overall memory footprint, and JVMs tend to have better ways to get at that via their logging & debugging hooks.

- 1
- 1

- 118,113
- 30
- 216
- 245
My answer is: there is no general solution to that. What you can do is:
boolean wasAlreadyInterned = str.intern() == str;
but this has the side-effect, that now it is interned for sure.
JavaDoc of String#intern
says, that the class String privately maintains a pool of strings, that is initially empty.
If you look at the implementation of the class String
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 the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method
String.intern
.

- 37,490
- 6
- 58
- 83
I think you have to look Pulling Strings from pool

- 4,706
- 9
- 36
- 50
-
4The `intern()` method can not be used to test whether a String is already in the pool, since it ensures that, after calling, the String **is** in the pool – Andreas Fester Apr 30 '13 at 18:46