java docs says:
A pool of strings, initially empty, is maintained privately by the
class String.
1) Is it a pool of string literals or references to these string literals? on net some articles refer it as pool of strings literals while other refer it as pool of references so i got confused.
2) Is string pool created per class basis or per JVM basis?
3)Is there any reference where i can find details of string pool, its implementation etc.?
1) Is it a pool of string literals or references to these string literals? on net some articles refer it as pool of strings literals while other refer it as pool of references so i got confused.
It is the same thing. You can't have a String object without a reference, or vice-versa.
And, as Peter Lawrey puts it: "In Java, an Object is inside the heap. Nowhere else. The only thing you can have inside something else, an object, an array, a collection or the stack, is a reference to that object."
2) Is string pool created per class basis or per JVM basis?
There is one String pool per JVM ... unless you are using some exotic JVM where they've decided to implement it differently. (The spec doesn't say that there has to be one string pool for the JVM, but that's generally the most effective way to do it.)
3)Is there any reference where i can find details of string pool, its implementation etc.?
You can download the complete source code of OpenJDK 6 or 7. The spring pool is implemented in native code ... so you'll be reading C++.
Is it a pool of string literals or references to these string literals?.
well, obviously it is pool of string literals. suppose you write,
String str= "a learner";
It will search in String pool by equals() method whether the same string is there in string pool or not.If it is there in Pool, that String object is returned, otherwise it is stored in String Pool and a reference to newly added string is returned.
So , it is pool of String objects, on which equals() method is called whenever you type a new string literal.
Is string pool created per class basis or per JVM basis?
There can be only one class of String in JVM because String class is final. So there is no question of more than one String class per JVM. Ultimately it comes out to be only one String Pool per JVM.
It's called String interning.
It is a pool of String literals
Interning is done on a JVM basis
The JDK source for String has all the code in there
Related
If jvm creates string pool for memory optimization, then why it creates new Object each time we create string using new keyword even though it exists in string pool?
... why does Java create new Object each time we create a string using the new keyword even though it exists in string pool?
Because you explicitly told it to! The new operator always creates a new object. JLS 15.9.4 says:
"The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created."
For the record, it is nearly always a mistake to call new String(String) ... but in obscure cases it might be useful. It is conceivable that you might want a string for which equals returns true and == gives false. Calling new String(String) will give you that.
For older versions of Java, the substring, trim and possibly other String methods would give you a string that shared backing storage with the original. Under certain circumstances, this could result in a memory leak. Calling new String(str.trim()) for example would prevent that memory leak, at the cost of creating a fresh copy of the trimmed string. The String(String) constructor guarantees to allocate a fresh backing array as well as giving you a new String object.
This behavior of substring and trim changed in Java 7.
To give primitive style of declaration and for performance designers introduced String literals.
But when you use new keyword, then you are explicitly creating objects on heap not in constant pool.
When the objects created on heap, there is no way to share that memory with each other and they become completely strangers unlike in constant pool.
To break this barrier between heap and constant pool String interning will help you out.
string interning is a method of storing only one copy of each distinct string value, which must be immutable
Remember that constant pool also a small part of heap with some additional benefits where sharing of memory is available.
When you write
String str = new String("mystring");
then it creates a string object in heap just like other object which you create. The string literal "mystring" is stored in the string constant pool.
From the Javadocs:
A pool of strings, initially empty, is maintained privately by the
class String.
When the intern method is invoked, if the pool already contains a
string equal to this String object as determined by the equals(Object)
method, then the string from the pool is returned. Otherwise, this
String object is added to the pool and a reference to this String
object is returned.
It follows that for any two strings s and t, s.intern() == t.intern()
is true if and only if s.equals(t) is true.
To take advantage of string pooling you need to use String#intern instead of new.
Following object will be stored in String pool :
String s = "hello";
And following object will be stored in Heap (not in string pool):
String s = new String ("hello")
To enforce garbage collection!. If you need some String just one time, then there is no point in keeping it in memory (for almost forever. Which is the case with Strings in constant pool). Strings which are not in the constants pool can be GCed like any other object. So, you should only keep frequently used Strings in the constants pool (by using literals or interning them).
Strings created in the form of String literals (String s = "string";) are stored in string pool, but Strings created by invoking String constructor using new (String s = new String("string");, are not stored in string pool.
I know how String pool works and all. That said:
void doSomething1(){
System.out.println("This string is now added to the string pool and will stay there even after this method returns");
}
void doSomething2(){
String msg = new String("This string is now added to the string pool and will stay there even after this method returns");
System.out.println(msg);
}
Is doSomething2 better than doSomething1. Should this be encouraged, given that some Strings have a very low chance of being reused. The problem I see is in case 1, the string stays in scope for extended period even when it is not used again.
Is doSomething2 better than doSomething1.
No.
Should this be encouraged, given that some Strings have a very low chance of being reused.
No.
The problem I see is in case 1, the string stays in scope for extended period even when it is not used again.
I think you are misunderstanding what is going on here.
The String "This string ... returns" is a String literal, and it is added to the string pool once and only once when the class containing those methods is loaded.
The doSomething1() does not add a String to the String pool. Rather, it uses an existing String (the one I mentioned above) that is already in the String pool.
The doSomething2() method makes a fresh copy of the original String that existed the String pool. You are correct that the copy created by doSomething2() is not in the string pool. However, you are not achieving anything useful by creating the copy in the first place. You are better off just using the original String.
Finally, it should be noted that the String in the string pool that was created when the class was loaded will stay there until the class is unloaded (if it is unloaded), or until the application finishes. There's nothing you can do about this ... and there's nothing you should be doing about this.
(The situation is analogous to what happens with a String literal in C or C++. A C / C++ String literal is represented as a sequence of bytes in the program's initialized constant area. It will be there for the duration of the program run, and there's nothing you can or should be doing to try to reclaim the space.)
But for the sake of understanding and completeness: Here is a big string which is only going to be used once and if I can keep it short scoped, why put it in the pool?
Because the JVM does not try to (and in the general case cannot) determine that the constant is only going to be used once. That kind of analysis is difficult, and it is not simply worth the effort.
For any sensible sized String literal, it is unlikely make any practical difference that it is in the pool for the duration. If the string literals are large enough or numerous enough that it does make a difference, then they should be replaced with strings that are read from resources on the classpath or elsewhere. It is up to the programmer to make this call ... not the JVM.
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.
String s = new String("Test");
does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.
In case of Java 7 you can use a new method to do so. It will put string in the pool for our convenience.
String myString="Hello StackOverflow";
myString.intern();
if(myString=="Hello StackOverflow")
System.out.println("Equal");
else
System.out.println("Not Equal");
String str1="JAVA";
String str2="JAVA";
String str3=new String("JAVA");
String str4=new String("JAVA").intern();
2 objects will be created. str1 and str2 refer to same object because of String literal pool concept and str3 points to new object because using new operator and str4 points to the same object points by str1 and str2 because intern() method checks into string pool for string having same value.
str1=str2=str3=str4=null;
One object will be eligible for GC. That is the object created through String str3=new String("JAVA"). The first String object is always accessible through reference stored in string literal pool.
Is my explanation correct?
Total Number of String objects created in the process?
Three: The one in the intern pool created via the literal and the two you create via new String.
One object will be eligible for GC.
I count two, and possibly even all three under very special circumstances:
The one you created in this line:
String str3=new String("JAVA");
(since you later set str3 to null).
The one you created temporarily in this line:
String str4=new String("JAVA").intern();
That line creates a new String object, calls intern on it, and then saves a reference to the string from the pool. So in theory, it creates a String object that is immediately available for GC. (The JVM may be smart enough not to do that, but that's the theory.)
Possibly, eventually, under the right conditions, even the string in the intern pool. Contrary to popular belief, strings in the intern pool are available for garbage collection as we can see from the answer to this other question. Just because they're in the permgen (unless you're using Oracle's JVM 7 or later) that doesn't mean they're not GC'd, since the permgen is GC'd too. So the question becomes: When or how is a string literal used in code no longer referenced? I don't know the answer, but I think a reasonable assumption would be: When and if the class using it is unloaded from memory. According to this other answer, that can only happen if both the class and its classloader are unloaded (and may not happen even then). If the class was loaded by the system classloader (the normal case), then presumably it's never unloaded.
So almost certainly just two (#1 and #2 above), but it was fun looking into #3 as well.
I heard that string object pool exists in the PermGC and when a string intern is executed, it checks the pool first to see if an equivalent string object exists, if it does not exist, it creates one and returns a reference to the pooled instance.
But here is my first question.
I think that object is created on the heap, especially in the young generation first. If it survives during few garbage collections, it moves to the old generation. can anybody explain how the string object goes to the pool that exists in the Perm GC?
second question:
String s = "test";
s = "test1";
If i reassign "test1" to a reference s and continue to use "test1", does it mean that "test" (created on the young generation) will be garbage collected?
third question:
How is the string object pool related to the runtime constant pool?
Thanks.
What makes you think the interned String first goes to the young generation? The String#intern() method is a native method. It's certainly very possible for an implementation to move it right into the permgen.
Second question: if there's no other references to that "test" String instance, it's eligible for garbage collection. Same story if it's interned. Even an interned String that no longer has any active references can be garbage collected. This might not have been the case in older JVMs, though. And it can be implementation-specific, I guess.
As for the third question, I do not know. All I know is that String literals from source code are placed into the same pool. If you were to construct a String that's equal to a String constant from source and then intern it, you'd be returned the instance that was used to represent the constant. Think of this as String literals having been interned right away.
EDIT: just read your initial few sentences again and I think I see the reason for the confusion. When you call intern() on a String, and no equal String is in the pool yet, then it's not first gonna construct an equivalent String. It'll just move the instance you called intern() on to the pool rather than returning a new reference. That's how it's stated in the JavaDoc.
Strings go to intern pool in two cases:
you explicitly call intern() method on the String object
you initialize it with a literal (you give the explicit content of the String), since Java automatically interns String literals.
The pool is organized as a table, once a String is interned it is added to the pool if the value is not yet present otherwise a reference to the existing entry is used.
"test" in your case is supposed to go to the pool and not to the young space, anyway cleanup of Strings not referenced anymore is performed there too (I cannot say if it is part of the same GC process used for the heap nor if this behavior is standard)
I have known that JVM maintains a string literal pool to increase performance and maintain JVM memory and learned that string literal is maintained in the string pool. But I want to clarify something related to the string pool and string object created on the heap.
Please correct me if my explanation is wrong.
String s = "abc";
If the above line is executed, "abc" string literal is added to the string pool if it does not exist in the pool. And string object is created on the heap and a reference s will point to the literal in the pool.
Questions:
Does this code create string object on the heap every time it is executed?
Does string literal pool maintain only string literals or does it maintain string object as well?
When does JVM decide that it needs to add string literal to the string pool? does it decide in the compile time or runtime?
I am not sure where exactly string object is created if it points to a string literal in the pool.
Thanks.
There is no "literal pool". Interned Strings are just normal heap objects. They may end up in the PermGen, but even then, they could eventually be garbage-collected.
The class file has a constant pool, which contains the String literals used in the class. When the class is loaded, String objects are created from that data, which is probably very similar to what String#intern does.
Does this code create string object on the heap every time it is executed?
No. There will be one String object that is being reused. It has been created when the class was loaded.
Does string literal pool maintain only string literals or does it maintain string object as well?
You can intern Strings as well. I assume that they are treated more or less the same.
When does JVM decide that it needs to add string literal to the string pool? does it decide in the compile time or runtime?
Literals are always "pooled". Other Strings need to have "intern" called on them. So in a way, the decision is made at compile-time.
Quoting documentation for String.intern()(emphasis mine)
All literal strings and string-valued constant expressions are
interned. String literals are defined in §3.10.5 of the Java Language
Specification
A pool of strings, initially empty, is maintained privately by the
class String.
When the intern method is invoked, if the pool already contains a
string equal to this String object as determined by the equals(Object)
method, then the string from the pool is returned. Otherwise, this
String object is added to the pool and a reference to this String
object is returned.
Thus,
Does this code create string object on the heap every time it is
executed?
Only one object is created for each unique interned string. All references share this immutable object.
Does string literal pool maintain only string literals or does it maintain string object as well?
There are no 'Literal Objects'. Literal string expressions when converted, are stored as regular String objects.Also, the pool contains all interned string objects. Both implicit (by using a string literal expression) and explicit (by calling .intern() on a String object).
When does JVM decide that it needs to add string literal to the string
pool? does it decide in the compile time or runtime?
I'm not sure.
I think there's something fundamental you're missing: the interned strings pool only contains String objects. Literals are not some sort of special object; at runtime they are just another String object.
Plus you can intern any String you want using String.intern(); it doesn't have to originate from a literal.
So regarding your questions:
No, there will be one String object allocated when the class is loaded.
It doesn't maintain any literals but rather String objects that were interned. Usually, those come from literals but in reality it could be any compile-time constant expression (String constant = "abc" + "def" would result in one String object "abcdef" at runtime).
They are compiled into the class file. So they are decided at compile time but obviously the objects themselves are created at runtime.
Does this code create string object on the heap every time it is executed?
Nope. Once created in the literal pool. The same referred again and again.
Does string literal pool maintain only string literals or does it maintain string object as well?
All are objects only, but objects created via assignment are put in pool where as the one created via new operator are put on heap.
When does JVM decide that it needs to add string literal to the string pool? does it decide in the compile time or runtime?
Whenever JVM comes across an expressions like
String str="Hello"; (string literal) or
String str="Hel" + "lo"; (string constant expression).
and the resultant string (str in this case) is not the pool, then in all such cases it adds the new string in the pool. This off course happens at runtime.
Check out this link.