To Write A Stack

来源:互联网 发布:mac怎么打开微博故事 编辑:程序博客网 时间:2024/06/05 03:17

To implement Stack.

This is actually Java homework. I thought it is would be insanely easy, though it is indeed not difficult. Just two things here:

1. I was totally familiar with Exceptions. Now I know a little and am kinda interested in it now.

2. About the method "clear()", I thought it would be enough to make head equal nullptr, then when I looked into the implements of LinkedList I found this:

//Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator

It seems that the second  reason here has nothing to do with stack. And the first reason, I don't know a thing. Maybe look into it later.


UPDATED on AUG.4.2017.

该注释中提到,清除链表中的所有节点有助于:

a.逐代回收中清理年龄大于1的废弃节点,即能够促进GC尽快回收废弃节点(为什么?Q2);

b.以及能够保证在即使有指向废弃节点的迭代器也能释放废弃节点所占的内存。

根据一个很久以前ORACLE官方发布的BUG(链接),在删除节点的相关操作中(包括remove,clear等),当时(2003年)的实现方式会导致链表中废弃节点的生存期过长(“Aroot entry node remaining in scope can keep a huge chain of referenced entries alive for considerably longer than is necessary.”),只有当root本身被回收以后废弃节点才会被回收。所以会导致内存溢出。该链接给出的解决方案是将废弃节点的next和previous均置为null,这样可以保证废弃节点被尽快回收。(其中的root指的时什么?Q2

我们可以看到,后来(至今)java在实现LinkedList的删除节点的相关操作中均会将所删除节点的next和previous置为null,(至少某种程度上)就是为了解决该BUG中提到的内存溢出问题。

不过,虽然尽量查阅了相关资料,但对于问题Q1Q2仍然不算清楚。总的来说,这个问题目前仍然没有解决,对于关于这一点上虚拟机的机制也缺乏足够的认识。



/** * Created by lyl-2017 on 2017/7/26. */public class AnotherStack<T> {    private class Node {        T value;        Node next;        Node(T value, Node next) {            this.value = value;            this.next = next;        }    }    private Node head = null;    private int size = 0;    public void push(T value) {        head = new Node(value, head);        ++size;    }    public T pop() {        if (head == null)            throw new EmptyStackException();        T e = head.value;        head = head.next;        --size;        return e;    }    public T peek() {        if (head == null)            throw new EmptyStackException();        return head.value;    }    public void clear() {        while(head!=null){            Node next = head.next;            head = null;            head = next;        }        size = 0;    }    boolean isEmpty() {        return head == null;    }    public int size() {        return size;    }}class EmptyStackException extends RuntimeException {    EmptyStackException() {        super();    }}


原创粉丝点击