I read that string constant pool is self referenced Also in this link it is written as the creation of String literal :
String s= "new";
will create a new String "new" in the heap if there is not one.
So does it mean that object is always created in the heap regardless its literal or new object using new keyword?
What i understood of intern is -- it checks if there is a object in the heap with same name then it is referenced else new object is created in the heap.
Please correct if i am wrong here.
Another doubt i have is - does the constant pool contains the objects or just the refernces to the objects in the heap.
does it mean that object is always created in the heap regardless its literal or new object using new keyword?
Yes, in Java all Object-derived objects, including Strings, are created in the heap. The only difference is that identical String objects from the constant pool get reused with the help of the compiler, while String objects created with operator new require explicit code from the programmer in order to get reused.
Yes it is on heap.
and with respect to intern() Yesyou are right.
Related
I have some questions revolving around the garbage collection of string objects and literals and the string pool.
Setup
Looking at a code snippet, such as:
// (I am using this constructor on purpose)
String text = new String("hello");
we create two string objects:
"hello" creates one and puts it into the string pool
new String(...) creates another, stored on the heap
Garbage collection
Now, if text falls out of scope and nobody references them anymore, it can be garbage collected, right?
But what about the literal in the pool? If it is not referenced by anyone anymore, can it be garbage collected as well? If not, why?
When we create a String via the new operator, the Java compiler will create a new object and store it in the heap space reserved for the JVM.
To be more specific, it will NOT be in the String Pool, which is a specialized part of the (heap) memory.
String text = new String("hello");
As soon as there is no more reference to the object it is eligible for GC.
In contrast, the following would be stored in the string pool:
String a = "hello";
When we call a similar line again:
String b = "hello";
The same object will be used from the String Pool, and it will never be eligible for GC.
As to why:
To reduce the memory needed to hold all the String literals (and the
interned Strings), since these literals have a good chance of being
used many times over.
The specification does not mandate a behavior. All it requires, is that all string literals (and string-typed compile-time constants in general) expressing the same string, evaluate to the same object at runtime.
JLS §3.10.5:
At run time, a string literal is a reference to an instance of class String (§4.3.3) that denotes the string represented by the string literal.
Moreover, 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.29) - are "interned" so as to share unique instances, as if by execution of the method String.intern (§12.5).
Its also repeated in JLS §15.29:
Constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern
This implies that each Java implementation maintains a pool at runtime which can be used to look up the canonical instance of the string. But the pool doesn’t have to hinder garbage collection. If no other reference to the object exists, the string instance could be garbage collected, as the fact that a new string instance has to be constructed when necessary, is unobservable.
Note that when you add strings to the pool manually, by invoking intern(), the string instances may indeed get garbage collected when otherwise being unreachable.
But in practice, the common implementations, like the HotSpot JVM associate a reference from the code location to the string instance after the first execution, so the object is referenced by the code containing the string literal or compile-time constant. So, the object associated with the string literal can only get garbage collected, when the class itself gets garbage collected. This is only possible when its defining class loader and in turn, all other classes defined by this loader are unreachable too.
For the application class loader, this is impossible. Class unloading can only happen for additional class loader created at runtime. Then, the string instances created for compile-time constants within classes loaded by this class loader may get garbage collected, if not matching constants in other code.
I learned about the Java String Pool recently, and there's a few things that I don't quiet understand.
When using the assignment operator, a new String will be created in the String Pool if it doesn't exist there already.
String a = "foo"; // Creates a new string in the String Pool
String b = "foo"; // Refers to the already existing string in the String Pool
When using the String constructor, I understand that regardless of the String Pool's state, a new string will be created in the heap, outside of the String Pool.
String c = new String("foo"); // Creates a new string in the heap
I read somewhere that even when using the constructor, the String Pool is being used. It will insert the string into the String Pool and into the heap.
String d = new String("bar"); // Creates a new string in the String Pool and in the heap
I didn't find any further information about this, but I would like to know if that's true.
If that is indeed true, then - why? Why does java create this duplicate string? It seems completely redundant to me since the strings in java are immutable.
Another thing that I would like to know is how the .intern() function of the String class works: Does it just return a pointer to the string in the String Pool?
And finally, in the following code:
String s = new String("Hello");
s = s.intern();
Will the garbage collector delete the string that is outside the String Pool from the heap?
You wrote
String c = new String("foo"); // Creates a new string in the heap
I read somewhere that even when using the constructor, the String Pool is being used. It
will insert the string into the String Pool and into the heap.
That’s somewhat correct, but you have to read the code correctly. Your code contains two String instances. First, you have the string literal "foo" that evaluates to a String instance, the one that will be inserted into the pool. Then, you are creating a new String instance explicitly, using new String(…) calling the String(String) constructor. Since the explicitly created object can’t have the same identity as an object that existed prior to its creation, two String instances must exist.
Why does java create this duplicate string? It seems completely redundant to me since the strings in java are immutable.
Well it does so, because you told it so. In theory, this construction could get optimized, skipping the intermediate step that you can’t perceive anyway. But the first assumption for a program’s behavior should be that it does precisely what you have written.
You could ask why there’s a constructor that allows such a pointless operation. In fact, this has been asked before and this answer addresses this. In short, it’s mostly a historical design mistake, but this constructor has been used in practice for other technical reasons; some do not apply anymore. Still, it can’t be removed without breaking compatibility.
String s = new String("Hello");
s = s.intern();
Will the garbage collector delete the string that is outside the String Pool from the heap?
Since the intern() call will evaluate to the instance that had been created for "Hello" and is distinct from the instance created via new String(…), the latter will definitely be unreachable after the second assignment to s. Of course, this doesn’t say whether the garbage collector will reclaim the string’s memory only that it is allowed to do so. But keep in mind that the majority of the heap occupation will be the array that holds the character data, which will be shared between the two string instances (unless you use a very outdated JVM). This array will still be in use as long as either of the two strings is in use. Recent JVMs even have the String Deduplication feature that may cause other strings of the same contents in the JVM use this array (to allow collection of their formerly used array). So the lifetime of the array is entirely unpredictable.
Q: I read somewhere that even when using the constructor, the String Pool is being used. It will insert the string into the String Pool and into the heap. [] I didn't find any further information about this, but I would like to know if that's true.
It is NOT true. A string created with new is not placed in the string pool ... unless something explicitly calls intern() on it.
Q: Why does java create this duplicate string?
Because the JLS specifies that every new generates a new object. It would be counter-intuitive if it didn't (IMO).
The fact that it is nearly always a bad idea to use new String(String) is not a good reason to make new behave differently in this case. The real answer is that programmers should learn not to write that ... except in the extremely rare cases that that it is necessary to do that.
Q: Another thing that I would like to know is how the intern() function of the String class works: Does it just return a pointer to the string in the String Pool?
The intern method always returns a pointer to a string in the string pool. That string may or may not be the string you called intern() or.
There have been different ways that the string pool was implemented.
In the original scheme, interned strings were held in a special heap call the PermGen heap. In that scheme, if the string you were interning was not already in the pool, then a new string would be allocated in PermGen space, and the intern method would return that.
In the current scheme, interned strings are held in the normal heap, and the string pool is just a (private) data structure. When the string being interned a not in the pool, it is simply linked into the data structure. A new string does not need to be allocated.
Q: Will the garbage collector delete the string that is outside the String Pool from the heap?
The rule is the same for all Java objects, no matter how they were created, and irrespective of where (in which "space" or "heap" in the JVM) they reside.
If an object is not reachable from the running application, then it is eligible for deletion by the garbage collector.
That doesn't mean that an unreachable object will be be garbage collected in any particular run of the GC. (Or indeed ever ... in some circumstances.)
The above rule equally applies to the String objects that correspond to string literals. If it ever becomes possible that a literal can never be used again, then it may be garbage collected.
That doesn't normally happen. The JVM keeps a hidden references to each string literal object in a private data structure associated with the class that defined it. Since classes normally exists for the lifetime of the JVM, their string literal objects remain reachable. (Which makes sense ... since the application may need to use them.)
However, if a class is loaded using a dynamically created classloader, and that classloader becomes unreachable, then so will all of its classes. So it is actually possible for a string literal object to become unreachable. If it does, it may be garbage collected.
According to Javadoc about String.intern():
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.
I have few questions about the same.
When a new String object (not using a string literal but using new() operator) is created like:
String str = new String("Test");
Question: I am aware that a new object will be created in heap. But will it also put String Test into the stringpool during object creation? If yes, then why the reference is not returned directly for the stringpool. If no, why not directly put the string in the pool as now the StringPool has been moved out of the PermGen and is in regular heap space (i.e. there is no space constraint apart from the heap space limit). There are some posts which state that the String is inserted in pool as soon as object is created whereas there are posts which contradicts this too.
Once we call String.intern() on a String object (as literals are already interned) what happens to the space allocated to the object? Is it reclaimed at the same moment or it waits for the next GC cycle?
Accepted answer to another question on SO, states that String intern should be used when you need speed since you can compare strings by reference (== is faster than equals).
Question: I am aware that when using String.intern() it returns reference to the string already present in the StringPool. But this requires a full scan lookup on the StringPool which can be an expensive operation in itself. So is this speed achieved during string comparison justifiable? If so, why?
I have looked at below sources:
JavaDoc
SO Question ques1, ques2, ques3
http://java-performance.info/string-intern-in-java-6-7-8/
And other misc sources from SO and outside world
All string literals are interned on compilation time. Using a string literal with the single argument constructor taking a string is a bit of an abuse of that constructor, hence you are likely to get two of them (but maybe there is a special compiler case for this, I can't say for sure). As of java 8 the implementation of the constructor (for openjdk) is this:
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
So no special treatment on this side. If you know the literal don't use this constructor.
I don't think there is any special GC semantics for Strings. It will get collected once it's unreachable and deemed collection worthy by the GC as any other object.
Don't ever use == for comparing strings, the first step in the default equals method for Strings is doing just that. If this is your dominant case (you know you are working with interned strings most of the time) you are only paying the overhead of a method call which is tiny, the potential for future bugs you add by doing something like that is just too big of a risk for a gain that is minuscule.
I have seen many questions regarding object created using string literal and new keyword like:
How many String objects using new operator
But it doesn't clarify my doubts.
Case 1: String object using string literal.
It creates one object in string constant pool if,it is not present otherwise, return the reference of this object.This object is implicitly interned.
Case 2:String object using new().
it creates 2 objects,one in string constant pool and another one in heap area.Reference variable refer to the heap area object.For this object we need to call intern method to put this object into string constant pool explicitly.
My question is if new() already creates one object in string constant pool then, what is use of calling intern method on the object which is there in heap area?
Case 2:String object using new(). it creates 2 objects,one in string constant pool and another one in heap area.
Only if you create a new String object by passing it a string literal, like this:
String s = new String("hello");
The literal "hello" will cause an object in the string constant pool to be created. The new String will create a new String object on the heap, with a copy of the content of the object for the literal.
You should never create String object like that, because it's unnecessary and inefficient.
There are however other reasons why you would want to do new String(...), when the value that you pass to the constructor is not a string literal. For example, the value is data read from a file.
Case 1: String object using string literal. It creates one object in string constant pool
Correct.
if,it is not present
Wrong. It is present.
otherwise, return the reference of this object.
It always return the reference of the object. No 'otherwise' about it.
This object is implicitly interned.
Not really. It is already interned, because it is a string literal. The compiler and class loader see to that. Not thenew operator.
Case 2:String object using new(). it creates 2 objects,one in string constant pool
Not really. It was already there: see above.
and another one in heap area.
Correct.
Reference variable refer to the heap area object.For this object we need to call intern method to put this object into string constant pool explicitly.
Correct.
My question is if new() already creates one object in string constant pool
It doesn't. See above.
Now I know this question is asked a lot of times, and has been answered many times, but still someone new to Java will find the explanation tough to understand.
So what I have understood from these question is as follows
String a = "hi";
The above statement first checks whether the string is present in string pool. If not, it adds it in the pool and a reference of it is created in the pool. Basically the object is made in permanent generation area and string pool is used to have a reference of it.
However, with
String a = new String("hello");
In this case, it creates two object. One in permanent generation area, and one in the normal heap memory. The a contains a reference to the heap memory object.
Now my question is whether this concept is right or not. Does string pool is references or a pool of actual strings and whether the concept of permanent generation area here I understood is right or not? If wrong please explain in layman's language. Please don't make it duplicate, as I already know this has been answered a lot of times. None was in layman's language and easy to understand. Are two objects actually made? If yes, then how, and if no, then why? It would be really helpful.
The effect of what you say is basically correct. The problem with your formulation concerns when things happen. When you write
String a="hi";
or indeed, your Java file has the string literal "hi" anywhere in it, then this string literal is allocated only once: when the class is loaded, when your code starts running. Then the initialization of a just uses the existing String object. But when you have an explicit constructor call as in
String a=new String("hi");
then a new String is created. new means a new string object.
Yes, you understand it well. When you do:
String a = new String("hello");
There will be 2 created Strings, one on the pool and one object, not in the pool that contains a copy of the content that's stored in the object from the pool.
You'll have something like that:
Pool
+-------+
|"hello" <-------- a
| |
+-------+
String a= new String("hello")
one object in string pool is created and one another object is created by new operator in heap area.and a is holding the reference of String pool object and string pool object is holding the reference of heap object. and heap object contains hello.