Java Theory and Practice

Source: Internet
Author: User
Tags aliases garbage collection resource first row

In languages where there is no garbage collection, such as C + +, you must pay special attention to memory management. For each dynamic object, you must either implement the reference count to simulate the garbage collection effect, or manage the "ownership" of each object to determine which class is responsible for deleting an object. Generally, the maintenance of such ownership has no written rules, but is maintained in accordance with the Convention (usually unwritten). Although garbage collection means that Java developers do not have to worry too much about memory leaks, sometimes we still need to worry about object ownership to prevent data contention (races) and unnecessary side effects. In this article, Brian Goetz points out some of the situations where Java developers must be aware of object ownership.

If you started learning programming before 1997, then maybe the first programming language you learned didn't provide transparent garbage collection. Each new operation must have a corresponding delete operation, or your program will leak memory, the final memory allocator (memory allocator) will fail, and your program will crash. Whenever you assign an object with new, you have to ask yourself, who will delete the object? When to delete?

Alias, also known as ...

The main reason for memory management complexity is alias usage: the same block of memory or object has multiple pointers or references. Aliases are naturally present at all times. For example, in Listing 1, the something object created in the first row of makesomething has at least four references:

Something reference.

There is at least one reference in the collection C1.

When something is passed as an argument to registersomething, a temporary asomething reference is created.

There is at least one reference in the collection C2.

Listing 1. Aliases in typical code

Collection c1, c2;

   public void makeSomething {
     Something something = new Something();
     c1.add(something);
     registerSomething(something);
   }
   private void registerSomething(Something aSomething) {
     c2.add(aSomething);
   }

There are two major memory management risks that you need to avoid in the non-garbage collection language: memory leaks and dangling pointers. To prevent memory leaks, you must ensure that each object that is allocated memory will eventually be deleted. To avoid dangling pointers (a dangerous case where a piece of memory has been freed and a pointer is still referencing it), the object must be deleted before the last reference is released. To meet these two constraints, it is important to adopt a certain strategy.

Managing object ownership for memory management

In addition to garbage collection, there are usually two other ways to handle alias problems: Reference counting and ownership management. A reference count (reference counting) is a count of how many references to a given object currently have, and then automatically deletes the object when the last reference is released. This is not possible automatically in most C + + versions prior to the mid 1990s. The Standard Template Library (Standard Template library,stl) allows the creation of "smart" pointers and does not automatically implement reference counts (see the Shared_ptr class in the open source Boost library for some examples, or see the simpler in the STL Auto_ptr Class).

Ownership management (ownership management) is a process that indicates that a pointer is a "owning" pointer ("owning" pointer), while all other aliases are only temporary two-class replicas (temporary second-class copies), and deletes the object only if the owning pointer is released. In some cases, ownership can be "shifted" from one pointer to another, such as a method that uses a buffer as a parameter to write data to a socket and deletes the buffer when the write operation completes. Such a method is often called a receiver (sinks). In this case, the ownership of the buffer has been effectively shifted, so the calling code must assume that the buffer has been deleted when the invoked method returns. (by ensuring that all alias pointers have scope (scope) consistent with the call stack, such as method parameters or local variables), you can further simplify ownership management and simplify by copying objects if the reference is to be saved by a variable that is not a stack scope. )

So, what's going on?

At this point, you may be wondering why I also discuss memory management, aliases, and object ownership. After all, garbage collection is one of the core features of the Java language, and memory management is a hassle that has become obsolete. Let the garbage collector take care of it, that's what it does. Those freed from the troubles of memory management are unwilling to go back to the past, and those who have never managed memory management simply cannot imagine how terrible programmers were in the past, such as 1996.

Beware of dangling aliases

So does this mean we can say goodbye to the concept of object ownership? You can say yes, or you can say no. In most cases, garbage collection does eliminate the need for explicit resource-storage-unit Allocations (explicit resource deallocation) (I'll discuss some exceptions in future columns). However, in one area, ownership management is still a problem in the Java program, and this is the dangling alias (dangling aliases) problem. Java developers often rely on the implicit assumption that object ownership determines which references should be considered read-only (a const pointer in C + +), and which references can be used to modify the state of the referenced object. A dangling pointer appears when two classes (wrongly) think that they are saving a unique writable reference to a given object. When this occurs, one or both of these two classes will be confused if the state of the object is accidentally changed.

Related Article

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.