Escape Analysis

Escape Analysis (EA) is another very important technique which Just-In-Time Java compiler can use to analyze the scope of a new object and decide whether it might not be allocated on Java heap space.

 

Many resources available on the internet say that EA allows objects to be allocated on the method stack. While technically they could be allocated on the stack, they are not in the current version of Java 8.

 

Official Java documentation says:

“It does not replace a heap allocation with a stack allocation for non-globally escaping objects.”

 

Fortunately, Escape Analysis allows JIT compiler to replace new object by unpacking its fields onto the stack, effectively performing kind of stack allocation. So instead of creating every single object on Java heap space, some of them can be “exploded” and the fields kept on the method stack or even in CPU registers instead of Java heap space. This is a very important performance optimization, because stack allocation and de-allocation are much faster than heap space allocation. But which objects can be kept like that?

 

Escape States

There are three escape states in which object can be:

  • NoEscape – when the object cannot be visible outside current method and thread
  • ArgEscape – when the object is passed as an argument to a method but cannot otherwise be visible outside the method or by other threads
  • GlobalEscape – when the object can escape the method or the thread. What it basically means is that object with GlobalEscape state will be visible outside method/thread. For instance, when the object is returned from the method or assigned to a static field

 

The optimization mentioned before can be easily applied on objects which have been classified during Escape Analysis as NoEscape.

 

In the snippet above, car is an example of object with NoEscape state – it is not visible nor accessible outside getCarDescription() method.

 

Locking and synchronization

Additionally, JIT compiler can remove some locking and memory synchronization overhead for NoEscape and ArgEscape objects, because these objects are only visible from the calling thread. A good example is an old synchronized StringBuffer in which synchronization can be removed if buffer object is classified as NoEscape or ArgEscape.

 

Escape Analysis is enabled by default with the Server compiler. To disable it, provide -XX:-DoEscapeAnalysis JVM flag.

 

5 responses to “Escape Analysis

  1. Hello friends, how is all, and what you want to say on the topic of this
    piece of writing, in my view its genuinely awesome designed for me.

  2. Hey, I think your blog might be having browser compatibility issues.
    When I look at your website in Safari, it looks fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to give you a quick
    heads up! Other then that, fantastic blog!

Leave a Reply

Your email address will not be published. Required fields are marked *