zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    Linux课程实践一:Linux基础实践(SSH)
    《恶意代码分析实战》读书笔记 静态分析高级技术一
    Linux课程实践四:ELF文件格式分析
    Linux课程实践三:简单程序破解
    Linux课程实践二:编译模块实现内核数据操控
    2020.12.19 加分项和课程意见/建议
    博客已换
    [题解] LuoguP4983 忘情
    [题解] LuoguP4767 [IOI2000]邮局
    [题解] LuoguP2791 幼儿园篮球题
  • 原文地址:https://www.cnblogs.com/linkarl/p/4808245.html
Copyright © 2011-2022 走看看