1

When a class is loaded by the bootstrap class loader from a class file, it adds to the string pool the strings contained in its constant pool.

However, what if I build my own class loader? How to ask to add a string literal into the string pool?

I don't think that String.intern() answers to my question since to do so, you already need to have a String.

Complementary question: who does take care of the string pool? I can read at http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#intern%28%29 that the class String has a pool of strings: is it the same one? Is it a static field?

Michu93
  • 5,058
  • 7
  • 47
  • 80
Codoscope
  • 892
  • 1
  • 10
  • 18

2 Answers2

2

The management of the string pool is part of the JVM and in no way triggered by class loaders. The mapping of compile-time constants to pooled runtime string instances doesn’t work via intern() either. It would be very inefficient to construct a new String instance each time, just to find an already existing one via intern().

Calling intern() can add additional instances to the JVM’s pool, but is not needed for strings that are already added to the pool of the JVM automatically.

Not only does the JVM map entries of the class’ constant pool to the runtime string pool, it’s also the JVM deciding when to do it. In case of HotSpot, it does not create and add String instances at load time, but on their first use.

Don’t take the sentence “A pool of strings … is maintained privately by the class String” too serious. There might have been times when there truly were fields in the String class for the pool management, perhaps in Java 1.0, but for a long time now, the pool is solely maintained by the JVM and String.intern() is a native method calling back into this facility. Besides the declaration of this intern() method, there is nothing the the String class dealing with this string pool.

If you want to implement a custom class loader, all you have to do, is to implement findClass and pass well formed class files to defineClass. You may additionally implement findResource[s] if your class loader has a notion of non-class resource, however, that’s on the nice-to-have side already.

Holger
  • 285,553
  • 42
  • 434
  • 765
0

All of the compile-time constant Strings in Java are automatically interned.(So they will be inserted into the StringTable (String pool))

Hope it's helped you. Further information about string interning on my blog: http://www.zoltanraffai.com/blog/?p=74

Zoltán Raffai
  • 127
  • 1
  • 10
  • The compiler can't internalize strings (it just adds them to the constant pool), the JVM does. My question is not about hardcoded strings but about on-the-fly created classes that reference strings. I think that `String.intern()` actually is the answer and that the string pool is the `String`'s pool of strings. And if a dynamically created class' bytecode contains strings, they will automatically be added to the strings pool. – Codoscope Jun 07 '17 at 10:03