NOTE
Escape Analysis
What escape analysis is, how to enable it, optimizations for non-escaping objects, lock elimination, scalar replacement, stack allocation, and references.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is Escape Analysis?
It analyzes the scope of an object.
There are two kinds of escape:
- Method escape: an object defined in the current method can be accessed by another method.
- Thread escape: an object defined in the current thread can be accessed by another thread.
2. How to Enable It
The JVM parameters for escape analysis are:
- Enable escape analysis:
-XX:+DoEscapeAnalysis - Disable escape analysis:
-XX:-DoEscapeAnalysis - Display analysis results:
-XX:+PrintEscapeAnalysis
Escape analysis is enabled by default.
3.2. Objects That Do Not Escape Can Be Optimized
3.2.1. Lock Elimination
Locks on objects that do not escape the thread can be eliminated.
For example, when using StringBuffer in a single-threaded situation, its synchronized operations can be eliminated.
The JVM parameters for lock elimination are:
- Enable lock elimination:
-XX:+EliminateLocks - Disable lock elimination:
-XX:-EliminateLocks
Lock elimination is enabled by default in JDK 8.
3.2.2. Scalar Replacement
- Scalar: primitive types and object references.
- Aggregate: objects.
If an object does not escape, it can be decomposed into scalars and allocated directly on the stack.
The JVM parameters for scalar replacement are:
- Enable scalar replacement:
-XX:+EliminateAllocations - Disable scalar replacement:
-XX:-EliminateAllocations - Display scalar-replacement details:
-XX:+PrintEliminateAllocations
Scalar replacement is also enabled by default in JDK 8.
3.2.3. Stack Allocation
If an object does not escape, it can be decomposed into scalars and allocated directly on the stack.
This is implemented through scalar replacement.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub