Writing in the front

Since we started learning Java, we have been exposed to the idea that objects in Java are created on the heap and references to objects are placed on the stack. Is this really true? If this is true, then why does the interviewer ask, “Are objects in Java necessarily allocated on the heap?” What about this problem? It seems that the idea we’ve been taught since we first encountered Java is worth questioning.

About the interview questions

The interview title in the title is: Are objects in Java all allocated on the heap?

When I first learned Java, I knew that objects in Java are created on the heap, and references to objects are stored on the stack, so objects in Java are allocated on the heap. Isn’t it?

If you answer that, you’ll be passed.

Maybe some of you still don’t understand, so let’s move on.

Answers to interview questions

First of all, we will give the answer to this question. Here I will briefly answer the interview question, and then we will conduct relevant analysis.

** You can answer this by saying that objects in Java are not necessarily allocated on the heap, because the JVM, through escape analysis, can figure out the scope of a new object and use that to determine whether or not to allocate that object to the heap. If the JVM finds that some object has no escape method, it is likely to be optimized for allocation on the stack. 六四清场

Here we encounter a new term: escape analysis. I believe many partners are not very clear, then we continue to look at.

Escape analysis

The concept of escape analysis

Let’s talk officially about what escape analysis is. Escape analysis is simply a static analysis that determines the dynamic range of a pointer, analyzing where a pointer can be accessed in a program.

In the just-in-time compile context of the JVM, escape analysis determines whether the newly created object escapes. Just-in-time compilation determines whether an object has escaped based on whether it has been stored in the heap (a static field or an instance field of an object in the heap) or whether it has been passed into unknown code.

It’s a little confusing to talk about these concepts, so let’s do two examples.

Object Escape example

A typical case of object escape is when an object is copied to a member variable or static variable, possibly for external use, and the variable escapes.

We can represent this phenomenon with the following code.

/ * * *@author binghe
 * @descriptionObject escape example 1 */
public class ObjectEscape{
    private User user;
    public void init(a){
        user = newUser(); }}Copy the code

In the ObjectEscape class, there is a member variable user. In init(), we create an object of class user and assign it to the member variable user. At this point, the object is copied to a member variable for possible external use, at which point the variable escapes.

Another typical scenario is when an object is returned by a return statement. If the object is returned by a return statement, the program is not sure whether the object will be used later. External threads can access the variable, and the object has escaped.

We can represent this phenomenon with the following code.

/ * * *@author binghe
 * @descriptionObject escape example 2 */
public class ObjectReturn{
    public User createUser(a){
        User user = new User();
        returnuser; }}Copy the code

To give you two examples, you may be familiar with the JVM’s escape analysis. Yes, the JVM uses escape analysis to determine whether new objects should be allocated on the heap or not.

That’s not all. Let’s continue to look at the advantages of escape analysis so that you can understand it better.

Advantages of escape analysis

The advantages of escape analysis generally fall into three categories: objects can be allocated on the stack, objects can be separated or scalar replaced, and synchronization locks can be eliminated. We can use the following figure.

Objects may be allocated on the stack

It is possible for the JVM to allocate objects on the stack by analyzing the scope of new objects through escape analysis. Stack allocation can quickly create and destroy objects on stack frames without allocating objects to heap space, effectively reducing the burden of JVM garbage collection.

Separate objects or scalar substitutions

When the JVM determines, through escape analysis, that an object needs to be allocated on the stack, just-in-time compilation can split the object and replace it with small local variables, a process we call scalar substitution. Once objects are replaced by local variables, they can be easily allocated on the stack.

Synchronization lock elimination

If the JVM, through escape analysis, finds that an object can only be accessed from one thread, then the object can be accessed without a synchronization lock. If a synchronized lock is used in your program, the JVM removes it.

It’s important to note here that this applies to synchronized locks, and that the JVM cannot eliminate Lock locks.

To enable sync elimination, add the -xx :+EliminateLocks parameter. Since this parameter depends on escape analysis, you should also turn on the -xx :+DoEscapeAnalysis option.

Therefore, not all objects and arrays are allocated on the heap, and due to just-in-time compilation, if the JVM finds that some objects do not have an escape method, it is likely to be optimized for allocation on the stack.

Big welfare

WeChat search the ice technology WeChat 】 the public, focus on the depth of programmers, daily reading of hard dry nuclear technology, the public, reply within [PDF] have I prepared a line companies interview data and my original super hardcore PDF technology document, and I prepared for you more than your resume template (update), I hope everyone can find the right job, Learning is a way of unhappy, sometimes laugh, come on. If you’ve worked your way into the company of your choice, don’t slack off. Career growth is like learning new technology. If lucky, we meet again in the river’s lake!

In addition, I open source each PDF, I will continue to update and maintain, thank you for your long-term support to glacier!!

Write in the last

If you think glacier wrote good, please search and pay attention to “glacier Technology” wechat public number, learn with glacier high concurrency, distributed, micro services, big data, Internet and cloud native technology, “glacier technology” wechat public number updated a large number of technical topics, each technical article is full of dry goods! Many readers have read the articles on the wechat public account of “Glacier Technology” and succeeded in job-hopping to big factories. There are also many readers to achieve a technological leap, become the company’s technical backbone! If you also want to like them to improve their ability to achieve a leap in technical ability, into the big factory, promotion and salary, then pay attention to the “Glacier Technology” wechat public account, update the super core technology every day dry goods, so that you no longer confused about how to improve technical ability!