Java uses soft references to block memory leaks

Source: Internet
Author: User
Tags garbage collection memory usage

In this article, he will explain another form of the Reference object, the soft reference (soft references), to help the garbage collector manage memory usage and eliminate potential memory leaks.

Garbage collection makes it possible for Java programs to have no memory leaks, at least for narrower "memory leak" definitions, but that does not mean that we can completely ignore object lifetime (Lifetime) issues in Java programs. Memory leaks usually occur in Java programs when we do not pay enough attention to the object Lifecycle (lifecycle) or destroy the standard mechanism for managing the lifecycle of objects. For example, the last time we saw that the life cycle of an object could not be divided, causing unexpected object retention when trying to associate metadata with an instantaneous object. There are other situations that can similarly ignore or destroy object lifecycle management and lead to memory leaks.

Object free

A form of memory leak, sometimes called object loitering, is illustrated by the Leakychecksum class in Listing 1, and in Listing 1 there is a getfilechecksum () method for calculating the checksum of the contents of the file. The Getfilechecksum () method reads the contents of the file into the buffer to compute the checksum. A more intuitive implementation simply allocates the buffer as a local variable in getfilechecksum (), but the version is more "intelligent" than that, rather than caching the buffer in the instance field to reduce the memory churn. This "optimization" usually does not bring the expected benefits; object allocation is cheaper than many people expect. (also note that the buffer is elevated from the local variable to the instance variable, so that the class is no longer thread-safe without additional synchronization.) Intuitive implementations do not need to declare getfilechecksum () as synchronized and provide better scalability at the same time as they are invoked. )

Listing 1. Class to show "Object Free"

// BAD CODE - DO NOT EMULATE
public class LeakyChecksum {
  private byte[] byteArray;
  public synchronized int getFileChecksum(String fileName) {
   int len = getFileSize(fileName);
   if (byteArray == null || byteArray.length < len)
    byteArray = new byte[len];
   readFileContents(fileName, byteArray);
   // calculate checksum and return it
  }
}

There are a lot of problems with this class, but we focus on memory leaks. The decision to cache a buffer is likely based on the assumption that the class will be called many times in a program, so it should be more efficient to reuse the buffer rather than redistribute it. As a result, the buffer will never be released because it is always accessible to the program (unless the Leakychecksum object is garbage collected). Worse, it can grow, but not shrink, so leakychecksum will permanently maintain a buffer as large as the maximum file being processed. In 10,000 steps, this will also put pressure on the garbage collector and require more frequent collection; Keeping a large buffer for computing future checksums is not the most efficient use of available memory.

The problem with Leakychecksum is that the buffer is logically local to the getfilechecksum () operation, but its lifecycle has been artificially extended because it has been elevated to the instance field. Therefore, the class must manage the lifecycle of the buffer itself, rather than having the JVM manage it.

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.