7

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?

angry_gopher
  • 1,613
  • 4
  • 17
  • 24

3 Answers3

4

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.

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
4

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.

jlordo
  • 37,490
  • 6
  • 58
  • 83
-1

I think you have to look Pulling Strings from pool

Sanjaya Liyanage
  • 4,706
  • 9
  • 36
  • 50
  • 4
    The `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