Java Theory and Practice: Talk about urban performance rumors

Source: Internet
Author: User
Java Theory and Practice: Talk about urban performance rumors

The shard ratio is expected to be faster and faster.

Source: http://www-128.ibm.com/developerworks/cn/java/j-jtp09275.html

 

 

Level: Intermediate

Brian Goetz (brian@quiotix.com), Chief Consultant, quiotix

October 20, 2005

Java has suffered many performance attacks. Although some attacks may be named, looking at the posts on the bulletin board and newsgroups, we can find that there are many misunderstandings about the actual working methods of Java Virtual Machine (JVM. In this month'sJava Theory and PracticeBrian Goetz refuted repeated rumors about slow JVM allocation. Share your thoughts on this article with the author and other readers in the related discussion group. (You can also clickDiscussionTo access the discussion group .)

Popular question: Which language features faster original allocation performance, Java or C/C ++? The answer may be surprising-the distribution ratio in modern JVM performs the bestmallocImplementation is much faster. In the virtual machine after hotspot 1.4.2new Object()The common code path can contain up to 10 machine commands (for more information about the data provided by Sun, see references), while the C language provides the best execution.mallocImplementation: The average number of commands required for each call is between 60 and 100 (detlefs, etc.; see references ). In addition, the allocation performance is not a negligible part of the overall performance. The evaluation shows that for many actual C and C ++ programs (such as Perl and ghostscript ), 20% to 30% of the overall execution time are spent inmallocAndfreeThere are far more overhead than healthy Java applications on allocation and garbage collection (Zorn; see references ).

Continue, make a mess

There is no need to search numerous blogs or Slashdot posts to find statements that can convince people like "garbage collection will never be as effective as direct memory management. In addition, in one aspect, these statements are true-dynamic memory management is not as fast-but much faster.malloc/freeThe technology processes one memory block at a time, while the garbage collection mechanism processes memory management in large batches to form more optimization opportunities (at some foreseeable losses ).

This "sound rational comment" (it is easier to clean up garbage in large batches than by a few o'clock a day later) is evidenced by data. A study (Zorn; see references) Measures replacement with conservative Boehm-Demers-Weiser (bdw) in many common C ++ applicationsmallocThe result is that many programs are running with garbage collection instead of the traditional distributor, which improves the speed. (Bdw is a conservative, non-mobile Garbage Collector that severely limits the ability to optimize allocation and recovery, and also limits the ability to improve the memory location; for example, the precise floating collectors used in JVM can be better .)

Allocation in JVM is not always so fast. Early JVM allocation and garbage collection performance were actually very poor. This is of course the origin of JVM allocation slowness. Early on, we saw a lot of "Slow allocation" comments-just like everything in the early JVM, it's really slow-performance Consultants offer a lot of tips to avoid allocation, such as object pools. (Public service declaration: Except for objects with the highest weight, the object pool is now a serious performance loss for all objects, it also requires a skill to use the object pool without causing a concurrency bottleneck .) However, many changes have taken place since JDK 1.0. The generation collector introduced in JDK 1.2 supports much simpler allocation methods, which greatly improves performance.

Generational garbage collection

The generational Garbage Collector divides the heap into multiple generations. Most JVMs use two generations: "Young Generation" and "Old Generation ". Objects are allocated in the young generation; if they still exist after a certain amount of garbage collection, they are treated as "long-lived" and promoted to the old generation.

Hotspot provides the choice of using three young generation collectors (Serial copy, parallel copy, and parallel cleaning). They all adopt the "copy" collector form and have several important common features. The copy collector divides the memory space from the middle into two halves, each of which uses only half. At the beginning, half of them constitute a large block of available memory. When a distributor meets the allocation request, it returns the first n Bytes of the space it does not use, and move the pointer (separated by "use") from the "free" part, as shown in the pseudo code in Listing 1. When the half used is full, the garbage collector copies all the active objects (not those in the garbage) to the bottom of the other half (compresses the heap into a continuous one ), then, allocate data from the other half.

Listing 1. Actions of the distributor when a copy collector exists

void *malloc(int n) {    if (heapTop - heapStart < n)        doGarbageCollection();    void *wasStart = heapStart;    heapStart += n;    return wasStart;}

From this pseudocode, we can see why the copy collector can achieve such a fast distribution-allocating new objects only checks whether there is enough space in the heap. If there is still, move the pointer. You do not need to search for the Free List, the best match, the first match, and the lookaside list. You only need to retrieve the first n Bytes from the heap.

How to recycle it?

But the allocation is only half of the memory management, and the recovery is the other half. For most objects, the cost of direct garbage collection is zero. This is because the copy collector does not need to access or copy dead objects and only processes active objects. Therefore, after allocation, it will soon become a garbage object, which will not cause the workload of the collection cycle.

In typical Object-oriented Programs, the vast majority of objects (between 92% and 98%, according to different studies) "die young", which means that after they are assigned, usually it will soon become garbage before the next garbage collection. (This property is calledGenerational hypothesis. For many object-oriented languages, it has been tested and proved to be true .) Therefore, not only must the allocation be fast, but also can be freely recycled for most objects.

Local thread allocation

If the allocator is fully implemented as shown in Listing 1, the sharedheapStartThe field quickly becomes a significant concurrency bottleneck, because each allocation requires a lock to protect this field. To avoid this problem, most JVMs useAllocate blocks locally by threadIn this case, each thread allocates a larger memory block from the heap, and then sequentially uses the local block of the thread to provide services for small allocation requests. Therefore, threads are greatly reduced in a large amount of time to obtain the shared heap lock, thus improving concurrency. (In the traditionalmallocIn the case of implementation, it is more difficult to solve this problem and the cost is higher. The thread support and garbage collection are both built into the platform to promote such collaboration .)


Stack allocation

C ++ provides programmers with the option to allocate objects in the heap or stack. Stack-based allocation is more effective: the allocation is cheaper and the collection cost is actually zero. Moreover, the language provides help to isolate the object lifecycle, reducing the risk of forgetting to release the object. On the other hand, in C ++, you must be very careful when releasing or sharing stack-based object references, because during stack frame arrangement, stack-based objects are automatically released, this leads to an exclusive pointer.

Another advantage of stack-based allocation is that it is more friendly to high-speed cache. In modern processors, the cost of cache omission is very significant, so if the language and runtime can help the program to achieve better data location, it will improve performance. The top of the stack is usually "hot" in the cache, while the top of the stack is usually "cold" (because it may take a long time since this part of the memory is used ). Therefore, allocating objects on the stack results in more cache omissions than allocating objects on the stack.

Worse, when allocating objects on the stack, there is a particularly annoying memory interaction in the cache omission. When allocating memory from the heap, No matter what content is left after the memory is used last time, the content in the memory is treated as garbage. If the memory block allocated at the top of the heap is not in the cache, execution will delay when the memory content is loaded into the cache. Then, we need to overwrite those values that are time-consuming and laborious to load the cache with 0 or other initial values, resulting in a waste of memory activity. (Some processors, such as Azul's Vega, include hardware support for accelerating heap allocation .)

Escape Analysis

Java statements do not provide any explicit way to allocate objects on the stack, but this fact does not affect JVM's ability to use stack allocation where appropriate. JVM can be calledEscape AnalysisThrough this technology, JVM can find that some objects are limited to a single thread throughout their lifecycle, you will also find that this lifecycle is bound to the lifecycle of the specified stack frame. Such objects can be securely allocated on the stack rather than on the stack. Better yet, for small objects, JVM can completely optimize the allocation, and only put the object fields into registers.

Listing 2 shows an example of using escape analysis to optimize heap allocation.Component.getLocation()Method To make a protective copy of the component location, so that the caller cannot inadvertently change the actual location of the component. CallgetDistanceFrom()Obtain the location of another component, including the allocation of objects, and then usegetLocation()ReturnedPointOfxAndyThe field calculates the distance between two components.

Listing 2. Typical protective copy method for returning compound values

public class Point {  private int x, y;  public Point(int x, int y) {    this.x = x; this.y = y;  }  public Point(Point p) { this(p.x, p.y); }  public int getX() { return x; }  public int getY() { return y; }}public class Component {  private Point location;  public Point getLocation() { return new Point(location); }  public double getDistanceFrom(Component other) {    Point otherLocation = other.getLocation();    int deltaX = otherLocation.getX() - location.getX();    int deltaY = otherLocation.getY() - location.getY();    return Math.sqrt(deltaX*deltaX + deltaY*deltaY);  }}

getLocation()The method does not know how its caller will handle the responsePoint; It is possible to get a reference pointing to point, such as placing it in the collection, sogetLocation()Adopts a protective encoding method. However, in this example,getDistanceFrom()It will not do this, it will only usePointIn a short time, and then release it, it looks like a waste of perfect objects.

The clever JVM will see the work to be done and optimize the allocation of protective copies. FirstgetLocation()Will become inlinegetX()AndgetY()The call is also processed, resulting ingetDistanceFrom()Will be as effective as listing 3.

Listing 3. pseudocode describes the result of applying inline optimization to getdistancefrom ().

  public double getDistanceFrom(Component other) {    Point otherLocation = new Point(other.x, other.y);    int deltaX = otherLocation.x - location.x;    int deltaY = otherLocation.y - location.y;    return Math.sqrt(deltaX*deltaX + deltaY*deltaY);  }

At this point, the escape analysis can show that the objects allocated in the first row will never be separated from its basic blocks.getDistanceFrom()It will never be modified.otherComponent status. (EscapeIt indicates that the object reference is not saved to the heap, or it is passed to unknown code that may retain a copy .) IfPointThe thread is actually local, and it is clear that its life cycle is limited within the basic block allocated to it, so it can be either stack allocation or completely optimized, see Figure 4.

Listing 4. pseudocode describes the results after the allocation is optimized from getdistancefrom ().

  public double getDistanceFrom(Component other) {    int tempX = other.x, tempY = other.y;    int deltaX = tempX - location.x;    int deltaY = tempY - location.y;    return Math.sqrt(deltaX*deltaX + deltaY*deltaY);  }

The result is the same performance that can be achieved when all fields are public, while ensuring the security provided by encapsulation and protective copy (among other secure coding technologies.

Escape Analysis in Mustang

Escape analysis is an optimization that has been discussed for a long time. It finally shows that escape analysis can be performed in the current build of Mustang (Java SE 6, and convert heap allocation to stack analysis (or not allocate) in the appropriate place ). Using escape analysis to clear some allocation results in faster average allocation time, simplified memory work, and fewer cache omissions. In addition, optimization of some distributions can reduce the pressure on the garbage collector, so that the collection can run less.

Even if stack allocation is not realistic in the source code, even if the language provides the allocation option, escape analysis can also find the chance of stack allocation, because the specific allocation will be optimized, it depends on how the results of the Methods returned by objects are actually used in a specific code path.getLocation()ReturnedPointIt may not be suitable for stack allocation in all cases, but once JVM is inlinegetLocation()It can optimize each call freely and independently, so as to provide the best results in both aspects: optimal performance, minimum time spent on low-level performance adjustment decisions.


Conclusion

JVM is good at discovering things that we always think only developers can know, which is shocking. Let the JVM select between stack allocation and heap allocation based on the actual situation, and we will be able to get the performance benefits of stack allocation, without having to bother programmers with stack allocation or heap allocation.

References

Learning

  • For more information, see the original article on the developerworks global site.

  • Java Theory and Practice: urban performance legends: explores some performance rumors and their sources.
  • Escape Analysis for Java: A paper presented by the IBM Research Institute on implementation of escape analysis at oopsla '99.
  • Garbage collection in JVM 1.4.1: This section describes the generation of garbage collection in hotspot.
  • A Brief History of garbage collection: Compare different garbage collection technologies, including the Copy technology used by hotspot for the young generation.
  • Garbage collection in the Java Virtual Machine: a demonstration on javaone 2003 that provides cost allocation data in hotspot.
  • Memory Allocation costs in large C and C ++ programs (detlefs, dosser, and Zorn): studies the costs allocated in many C and C ++ applications.
  • The measured cost of conservative garbage collection (Benjamin Zorn): compares the performance of several splitters in C and C ++, including the bdw collector.
  • Java Theory and Practice: A complete series of articles by Brian Goetz.
  • Java Technology Zone: hundreds of articles on Java programming.

Obtain products and technologies

  • The Boehm-Demers-Weiser conservative Garbage Collector for C: Garbage collection can be used in C; bdw collector ismalloc()Andfree()Instead, it uses the garbage collection heap.

Discussion

  • Participate in Forum discussions.

  • Developerworks blogs: Join the developerworks community.

About the author

 

Brian Goetz has been a professional software developer for more than 18 years. He is the chief consultant of quiotix, a software development and consulting company located in Los Altos, California. He is also working in multiple JCP expert groups. Refer to the articles Brian has published and to be published in popular industry publications.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.