zoukankan      html  css  js  c++  java
  • Effective Java 06 Eliminate obsolete object references

    NOTE

    1. Nulling out object references should be the exception rather than the norm.
    2. Another common source of memory leaks is caches.

      Once you put an object reference into a cache, it's easy to forget that it's there and leave it in the cache long after it becomes irrelevant. There are several solutions to this problem. If you're lucky enough to implement a cache for which an entry is relevant exactly so long as there are references to its key outside of the cache, represent the cache as a WeakHashMap; entries will be removed automatically after they become obsolete. Remember that WeakHashMap is useful only if the desired lifetime of cache entries is determined by external references to the key, not the value. (LinkedHashMap can remove the oldest cache item by reomveEldestEntry. More is in java.lang.ref)

    3. A third common source of memory leaks is listeners and other callbacks.

       

    // Can you spot the "memory leak"?

    public class Stack {

    private Object[] elements;

    private int size = 0;

    private static final int DEFAULT_INITIAL_CAPACITY = 16;

    public Stack() {

    elements = new Object[DEFAULT_INITIAL_CAPACITY];

    }

    public void push(Object e) {

    ensureCapacity();

    elements[size++] = e;

    }

    public Object pop() {

    if (size == 0)

    throw new EmptyStackException();

    Object result = elements[--size];

    elements[size] = null; // Eliminate obsolete reference

    return result;

    }

    /**

    * Ensure space for at least one more element, roughly

    * doubling the capacity each time the array needs to grow.

    */

    private void ensureCapacity() {

    if (elements.length == size)

    elements = Arrays.copyOf(elements, 2 * size + 1);

    }

    }

    作者:小郝
    出处:http://www.cnblogs.com/haokaibo/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    安装mysql警告 warning: mysql-community-server-5.7.19-1.el6.x86_64.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
    RPM方式安装MySQL5.6
    CentOS7安装MySQL冲突和问题解决小结
    Linux(64) 下 Tomcat + java 环境搭建
    自写Jquery插件 Combobox
    自写Jquery插件 Datagrid
    自写Jquery插件 Menu
    scrapy 中间件
    提高scrapy爬取效率配置
    scrapy基于请求传参实现深度爬取
  • 原文地址:https://www.cnblogs.com/haokaibo/p/eliminate-obsolete-object-references.html
Copyright © 2011-2022 走看看