Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check String Pool Contents?

Is there any way to check, currently which Strings are there in the String pool.

Can I programmatically list all Strings exist in pool?

or

Any IDE already have this kind of plugins ?

like image 700
Ninad Pingale Avatar asked Jun 05 '14 06:06

Ninad Pingale


People also ask

How do you check pool strings?

The string constant pool is there is create a bit of efficiency for constant strings that can be known at compile-time. Other than that it doesn't matter. You should always compare strings with equals().

Does garbage collector clean string pool?

Second, in fact the rules for garbage collecting objects in the string pool are the same as for other String objects: indeed all objects. They will be garbage collected if the GC finds them to be unreachable.

Where is string pool stored?

As the name suggests, String Pool in java is a pool of Strings stored in Java Heap Memory.

What is string pool explain with example?

A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored. When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap.


1 Answers

You are not able to access the string pool from Java code, at least not in the HotSpot implementation of Java VM.

String pool in Java is implemented using string interning. According to JLS §3.10.5:

a string literal always refers to the same instance of class String. This is because 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.

And according to JLS §15.28:

Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.

String.intern is a native method, as we can see in its declaration in OpenJDK:

public native String intern(); 

The native code for this method calls JVM_InternString function.

JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))     JVMWrapper("JVM_InternString");     JvmtiVMObjectAllocEventCollector oam;     if (str == NULL) return NULL;     oop string = JNIHandles::resolve_non_null(str);     oop result = StringTable::intern(string, CHECK_NULL);     return (jstring) JNIHandles::make_local(env, result); JVM_END 

That is, string interning is implemented using native code, and there's no Java API to access the string pool directly. You may, however, be able to write a native method yourself for this purpose.

like image 136
izstas Avatar answered Sep 19 '22 06:09

izstas