5

I want to monitor the strings in Java String constant pool. But I don't know a method to resolve the problem. Thanks!

Guo Song
  • 352
  • 1
  • 11
  • 2
    It is better to re-think why you want this. Perhaps there is another way to solve this. – Peter Lawrey Aug 02 '14 at 09:06
  • Now, the string pool is empty, after it executes `String str = new String("hello");` in JDK 7, the string pool contains string **hello**? – Guo Song Aug 02 '14 at 09:11
  • 2
    The string pool is never empty. It will always have many strings in the pool as these are trigged just loading the JVM. – Peter Lawrey Aug 02 '14 at 09:19
  • Ok, but could you give me an answer about my question above? – Guo Song Aug 02 '14 at 09:39
  • The simplest solution is to build your own version of OpenJDK as the string pool is an internal structure in native memory, and add some native methods which expose the information you want. – Peter Lawrey Aug 02 '14 at 09:44
  • 1
    "*after.. `new String("hello");` the string pool contains string hello?*" yes, because you used string literal `"hello"` as argument of `new String(...)` constructor. This literal will be (if it wasn't already been) placed in String pool. If you would use instead something like `new String(new char[]{'h', 'e', 'l', 'l', 'o'})` (there is no string literal as argument now, but simple array of characters) then this constructor will return `"hello"` string, but will not place it in String pool. – Pshemo Aug 02 '14 at 11:08
  • Use [PrintStringTable](https://github.com/puneetlakhina/javautils/blob/master/src/com/blogspot/sahyog/PrintStringTable.java), I print all the strings in constant pool, thanks. – Guo Song Aug 02 '14 at 12:36

0 Answers0