Recently achieved a topic:
Question: String str = new String ("abc"), How is "ABC" Allocated in memory? The answer is: heap, string constant area.
The topic examines the concepts associated with string constant pools in Java and the runtime data area of the JVM. "ABC" is a literal object that is stored in heap memory. The string constant pool stores a reference to a string object.
string constant pool in Java
There are two forms of string object creation in Java, one for the literal form, and the other for the use of the String str = "droid"; standard constructed object of new, such as String str = new String("droid"); these two ways that we often use in code writing, especially in the literal way. However, there are some differences in performance and memory consumption between the two implementations. It all started with the JVM. In order to reduce the duplication of string objects, it maintains a special memory, which is a string constant pool or string literal pool.
Working principle
When a string object is created in the literal form of the code, the JVM first checks the literal, and if a reference to a string object of the same content exists in the string constant pool, the reference is returned, otherwise the new string object is created, then the reference is placed into the string constant pool, and the reference is returned.
Examples of literal creation form string str1= "Droid";
The JVM detects this literal, and here we think there is no content for droid the object to exist. The JVM finds the existence of a string object that does not exist by string constant pool, then droid creates the string object and then puts a reference to the object you just created into the string constant pool and returns the reference to the variable str1.
If there is a piece of code that follows:
[Java]View PlainCopy
- String str2="Droid";
The JVM also detects this literal, and the JVM finds the existence of the "Droid" string object by finding the string constant pool, and returns the reference to the variable str2 for the existing string object. Note that new string objects are not recreated here.
To verify that str1 and str2 point to the same object, we can pass this code
[Java]View PlainCopy
- System.out.println (STR1==STR2);
Output: True.
Create with new
[Java]View PlainCopy
- String str3=new String ("Droid");
When we use new to construct a string object, a new string object is created, regardless of the reference to the object with the same content in the string constant pool. So let's test it with the code below,
[Java]View PlainCopy
- System.out.println (STR1==STR3);
The result returns: False to indicate that the two variables point to a different object.
Intern
For the string object created above using new, you can use the Intern method if you want to add a reference to this object to the string constant pool. After calling intern, first check to see if there is a reference to the object in the string constant pool, and if so, return the reference to the variable, otherwise the reference is added and returned to the variable.
[Java]View PlainCopy
- String Str4=str3.intern ();
- System.out.println (STR4==STR1);
[Java]View PlainCopy
- The output is true.
What are the prerequisites for a difficult problem?
The precondition of a string constant pool implementation is that the string object in Java is immutable, which ensures that multiple variables share the same object safely. If a string object in Java is mutable, and a reference operation alters the value of the object, then the other variables are affected, which is obviously unreasonable.
Referencing or objects
It is the most common problem that a string constant pool holds references or objects. A string constant pool holds an object reference, not an object. In Java, objects are created in heap memory.
Please refer to the original text for verification.
Advantages and Disadvantages
The advantage of a string constant pool is to reduce the creation of the same content string, saving memory space.
If hard to say the disadvantage, it is to sacrifice the CPU computing time to change space. CPU compute time is primarily used to look up a reference in a string constant pool for the content of the same object. However, its internal implementation is Hashtable, so the computational cost is lower.
GC Recycling?
Because a string constant pool holds a reference to a shared string object, does that mean that these objects cannot be recycled?
The objects that are shared in the first question are generally small. As far as I am aware, this problem does exist in earlier versions, but with the introduction of weak references, the problem should not be present.
On this issue, you can learn more about this article interned Strings:java Glossary
Intern use?
The premise of using intern is that you know you really need to use it. For example, we have a record of millions of records, one of which has been recorded several times in the state of California, and we do not want to create a string object like millions, and we can use intern to keep only one copy in memory. For more in-depth understanding of intern, please refer to the in-depth parsing string#intern.
There's always an exception?
Do you know the following code that creates several string objects and saves a few references in a string constant pool?
String test = "a" + "B" + "C";
The answer is that only one object is created and only one reference is saved in the constant pool. We can see it by using JAVAP anti-compilation.
[Java]View PlainCopy
- :$ javap-c TESTINTERNEDPOOLGC
- Compiled from "Testinternedpoolgc.java"
- Public class TESTINTERNEDPOOLGC extends java.lang.object{
- public TESTINTERNEDPOOLGC ();
- Code:
- 0:aload_0
- 1:invokespecial #1; //method java/lang/object. " <init> ":() V
- 4: return
- Public static void Main (java.lang.string[]) throws java.lang.Exception;
- Code:
- 0:LDC #2; //string ABC
- 2:astore_1
- 3: return
See, actually, during compilation, these three literals have been synthesized in one. This is actually an optimization, avoiding the creation of redundant string objects, and the problem of string stitching does not occur. For string stitching, you can view Java details: concatenation of strings.
The difference between heap and Stack in Java
When a person begins to learn Java or other programming languages, it comes into contact with heaps and stacks, and since there is no clear explanation at first, many people will have many questions, what is a heap, what is a stack, and what is the difference between a heap and a stack? To make things worse, there is a data structure in Java that is in the order of a last-in, first-out, which is java.util.Stack. In this case, it inevitably makes many people more puzzled by the previous question. In fact, the heap and stack are all part of the memory, have different functions, and a program needs to allocate memory on this area. As we all know, all Java programs run inside the JVM virtual machine, and what we are describing here is naturally the heap and stack in the JVM (virtual) memory.
Difference
The difference between heap and stack in Java is naturally a common problem in the interview, the following points are the specific differences
Perform their duties
The main difference is that stack memory is used to store local variables and method calls.
Heap memory is used to store objects in Java. Whether they are member variables, local variables, or class variables, the objects they point to are stored in heap memory.
Exclusive OR shared
Stack memory belongs to a single thread, each thread will have a stack of memory, its stored variables can only be seen in its own thread, that is, stack memory can be understood as a thread of private memory.
Objects in the heap memory are visible to all threads. Objects in the heap memory can be accessed by all threads.
Exception error
If the stack memory does not have space to store method calls and local variables, the JVM throws Java.lang.StackOverFlowError.
And if the heap memory does not have space available to store the generated objects, the JVM throws Java.lang.OutOfMemoryError.
Space size
The memory of the stack is much smaller than the heap memory, and if you use recursion, your stack will soon be filled. If recursion does not jump out in time, stackoverflowerror problem is likely to occur.
You can set the stack memory size with the-XSS option. The-XMS option sets the size at which the heap starts, and the-XMX option sets the maximum value for the heap.
This is the difference between heap and Stack in Java. Understanding this problem can help you solve problems in development, analyze heap memory and stack memory usage, and even performance tuning.
Translation Information
Authentic English Original: http://javarevisited.blogspot.com.au/2013/01/difference-between-stack-and-heap-java.html.
string constant pool in Java