有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用classmexer查找java中自定义堆栈的内存使用情况

我编写了一些代码来确定各种数据结构占用的内存。我使用classmexerapi来获取深/浅内存。我尝试了对使用内部类节点实现的自定义整数堆栈的调用。(我正在ubuntu lucid上运行此操作)

对于空堆栈,浅内存和深内存都是16字节 对于4个整数的堆栈,深度内存为176字节。这个数字让我困惑,因为手工计算的记忆如下

4个整数的堆栈:

object overhead = 16 bytes
reference to Node inst variable = 8
primitive type int variable = 4
padding = 4
total = 32

Each entry in stack has
Node = 40 bytes(inner class)
Integer field = 24 
total = 64

所以,它应该是32+64N

对于N=4,这将是288

那么,为什么classmexer将内存使用率显示为176

还有一件事。。如何确定系统上的machine word size。我查看了lang.System类,但找不到任何用于该类的api

这是我的密码

public class MemoryUsage {
    private static void linkedListMemUsage(){
        StackOfIntegers si1 = new StackOfIntegers();

        long deepmem = MemoryUtil.deepMemoryUsageOf(si1);
        long shallowmem = MemoryUtil.memoryUsageOf(si1);

        System.out.println("\nfor an empty stack of integers");
        System.out.println("*******************************");
        System.out.println(si1.getClass().getSimpleName()+" took deep:"+deepmem+" bytes");
        System.out.println(si1.getClass().getSimpleName()+" took shallow:"+shallowmem+" bytes");

        StackOfIntegers si2 = new StackOfIntegers();
        si2.push(new Integer(100));
        si2.push(new Integer(200));
        si2.push(new Integer(300));
        si2.push(new Integer(400));

        deepmem = MemoryUtil.deepMemoryUsageOf(si2);
        shallowmem = MemoryUtil.memoryUsageOf(si2);

        System.out.println("\nfor a stack of 4 integers");
        System.out.println("*************************");
        System.out.println(si1.getClass().getSimpleName()+" took deep:"+deepmem+" bytes");
        System.out.println(si1.getClass().getSimpleName()+" took shallow:"+shallowmem+" bytes");


    }
    public static void main(String[] args) {
        linkedListMemUsage();
    }
    class StackOfIntegers{
        private int N;
        private Node first;

        public void push(Integer item){
        Node old = first;
        first = new Node();
        first.item = item;
        first.next = old;
        N++;
        }
        private class Node{
            Integer item;
            Node next;
        }
    }
}

共 (0) 个答案