The popularity of the Java programming language has made escape analysis a target of interest. Java's combination of heap-only object allocation, built-in threading, and the Sun HotSpot dynamic compiler creates a candidate platform for escape analysis related optimizations. Escape analysis is implemented in Java Standard Edition 6.
Example (Java)
class A {
final int finalValue;
public A( B b ) {
super();
b.doSomething( this ); // this escapes!
finalValue = 23;
}
int getTheValue() {
return finalValue;
}
}
class B {
void doSomething( A a ) {
System.out.println( a.getTheValue() );
}
}
In this example, the constructor for class A passes the new instance of A to B.doSomething
. As a result, the instance of A—and all of its fields—escapes the scope of the constructor.
Java is able to manage multithreading at the language level. Multithreading is a technique that allows programs to operate faster on computer system that have multiple CPUs. Also, a multithreaded application has the ability to remain responsive to input, even when it is performing long running tasks.
However, programs that use multithreading need to take extra care of objects shared between threads, locking access to shared methods or blocks when they are used by one of the threads. Locking a block or an object is a time-consuming operation due to the nature of the underlying operating system-level operation involved .
As the Java library does not know which methods will be used by more than one thread, the standard library always locks blocks when necessary in a multithreaded environment.
Prior to Java 6, the virtual machine always locked objects and blocks when asked to by the program even if there was no risk of an object being modified by two different threads at the same time. For example, in this case, a local Vector was locked before each of the add operations to ensure that it would not be modified by other threads (Vector is synchronized), but because it is strictly local to the method this is not necessary:
public String getNames() {
Vector v = new Vector();
v.add("Me");
v.add("You");
v.add("Her");
return v.toString();
}
Starting with Java 6, code blocks and objects are locked only when necessary , so in the above case, the virtual machine would not lock the Vector object at all
Escape analysis and lock coarsening in JAVA 6.0