Search code examples
javajvmclassloaderstring-pool

How to add a string to the string pool


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?


Solution

  • 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.