Effective Java 英文 第二版 读书笔记 Item 6:Eliminate obsolete object references

 

package eliminateObsoleteObject;

import java.util.EmptyStackException;

//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 o) {
        ensureCapacity();
        elements[size++] = o;
    }

    public Object pop(Object o) {
        if (size == 0) {
            throw new EmptyStackException();
        }
        // Object result=elements[--size];
        // elements[size]=null;//Eliminate obsolete reference
        // return result;
        return elements[--size];
    }

    /**
     * Ensure space for at least one more element,roughly doubling the capacity
     * each time the array needs to grow.
     */
    private void ensureCapacity() {
        // TODO Auto-generated method stub

    }

}

 

Nulling out object references should be the exception rather than the norm.

 

Generally speaking,whenever a class manages its own memory,the programmer should be alert for memory leaks.Whenever an element is freed,any object references contained it the element should be nulled out.

Another common source of memory leaks is caches.

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

 

Because memory leaks typically do not manifest themselves as obvious failures,they may remain present in a system for years.They are typically discovered only as a result of careful code inspection or with the aid of a debugging tool known as a heap profiler.Therefore,it is very desirable to learn to anticipate problems like this before they occur and prevent them form happening.

转载于:https://www.cnblogs.com/linkarl/p/4808245.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值