How can I destroy reference from String pool in Java?

后端 未结 1 574
旧时难觅i
旧时难觅i 2021-01-20 01:08

Strings are immutable. When I declare:

String a = \"abc\";
String a1 = \"abc\";

Both objects refer to same location. So how can I destroy t

1条回答
  •  梦毁少年i
    2021-01-20 01:14

    No, typically you can not "destroy reference from String pool in Java" manually.

    The main reason I suppose why you are targeting it is to avoid out of memory errors. In Java 6 days all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool. Besides explicitly interned strings, PermGen string pool also contained all literal strings earlier used in your program. The biggest issue with string pool in Java 6 was its location – the PermGen. PermGen has a fixed size and can not be expanded at runtime. You can set it using -XX:MaxPermSize=N option. This would lead to memory leaks and out of memory errors.

    In Java 7 – the string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects.

    You may also increase the string pool size by configuring -XX:StringTableSize=N. If you are not sure about the string pool usage, try -XX:+PrintStringTableStatistics JVM argument. It will print you the string pool usage when your program terminates.

    In JDK, there is also a tool named jmap which can be used to find out number of interned strings in your application.

    jmap -heap process_id
    

    Eg:

    jmap -heap 18974
    

    Along with other output, this command also outputs number of interned strings and the space they occupy "xxxxxx interned Strings occupying xxxxxx bytes."

    The rules for garbage collection of objects in the String pool are the same as for other Strings or any other object. But the fact that the String objects that correspond to String literals mostly are always reachable since there is an implicit reference to the string object in the code of every method that uses the literal and so typically they are not candidates for garbage collection. However, this is not always the case. If the literal was defined in a class that was dynamically loaded (e.g. using Class.forName(...)), then it is possible to arrange that the class is unloaded. If that happens, then the String object for the literal will be unreachable, and will be reclaimed when the heap containing the interned String gets GC'ed.

    0 讨论(0)
提交回复
热议问题