浅谈JVM内存结构原理(堆栈方法区)

  • https://jingyan.baidu.com/article/6c67b1d6a09f9a2786bb1e4a.html 参考
  • http://www.open-open.com/lib/view/open1432200119489.html 参考 http://blog.csdn.net/joe_007/article/details/38964407

主要内容:

       本文分为堆(heap)、栈(stack)、方法区(method)、堆栈区别、直接内存这五个部分,分别来讲解一下这些内容。

1.堆:

       堆是计算机科学中一类特殊的数据结构的统称堆通常是一个可以被看做一棵树的数组对象。

堆中某个节点的值总是不大于或不小于其父节点的值,

堆总是一棵完全二叉树

将根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆。常见的堆有二叉堆、斐波那契堆等。堆是在程序运行时,而不是在程序编译时,申请某个大小的内存空间,即动态分配内存,对其访问和对一般内存的访问没有区别。堆是应用程序在运行的时候请求操作系统分配给自己内存,一般是申请和给予的过程,堆是指程序运行时申请的动态内存。

2.栈:

        从两个问题开始说,什么是栈?又该怎么理解呢?栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。栈就是一个桶,后放进去的先拿出来,它下面本来有的东西要等它出来之后才能出来(先进后出规则)栈也是操作系统在建立某个进程时或者线程(在支持多线程的操作系统中是线程)为这个线程建立的存储区域,该区域具有FIFO的特性,在编译的时候可以指定需要的Stack的大小。

        由此延伸出一个词——堆栈:什么是堆栈?又该怎么理解呢?其实堆栈本身就是栈,只是换了个抽象的名字。堆栈的特性: 最后一个放入堆栈中的物体总是被最先拿出来, 这个特性通常称为后进先出(LIFO)队列。 堆栈中定义了一些操作。 两个最重要的是PUSH和POP。 PUSH操作在堆栈的顶部加入一 个元素。POP操作相反, 在堆栈顶部移去一个元素, 并将堆栈的大小减一。

3.方法区:

        方法区又叫静态区,跟堆一样,被所有的线程共享。方法区包含所有的class和static变量。方法区中包含的都是在整个程序中永远唯一的元素,如class,static变量。

   4.堆栈区别:

1.堆栈空间分配

 ①栈(操作系统):由操作系统自动分配释放 ,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。

 ②堆(操作系统): 一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收,分配方式倒是类似于链表。

2.堆栈缓存方式

①栈使用的是一级缓存, 他们通常都是被调用时处于存储空间中,调用完毕立即释放。

②堆则是存放在二级缓存中,生命周期由虚拟机的垃圾回收算法来决定(并不是一旦成为孤儿对象就能被回收)。所以调用这些对象的速度要相对来得低一些。

3.堆栈数据结构区别

①堆(数据结构):堆可以被看成是一棵树,如:堆排序。

②栈(数据结构):一种先进后出的数据结构。


   5.直接内存:

      在Hotspot JVM上,我们能够直接对内存进行读写操作。该类的allocateMemory方法用于申请分配内存,putAddress和getAddress方法用于对直接内存进行读写。注意:这只是一个例子,只是用来验证通过sun.misc.Unsafe来实现直接读写内存的可能性。但是,这样做并没有安全保证,而且稍微有点疏忽将可能导致JVM崩溃。 
Unsafe类的三个方法:allocateMemory,putAddress和getAddress如下:
/** 
          * Fetches a native pointer from a given memory address.  If the address is 
          * zero, or does not point into a block obtained from {@link 
          * #allocateMemory}, the results are undefined. 
          * 
          * <p> If the native pointer is less than  bits wide, it is extended as 
          * an unsigned number to a Java long.  The pointer may be indexed by any 
          * given byte offset, simply by adding that offset (as a simple integer) to 
          * the long representing the pointer.  The number of bytes actually read 
          * from the target address maybe determined by consulting {@link 
          * #addressSize}. 
          * 
          * @see #allocateMemory 
          */  
         public native long getAddress(long address);  
       
         /** 
          * Stores a native pointer into a given memory address.  If the address is 
          * zero, or does not point into a block obtained from {@link 
          * #allocateMemory}, the results are undefined. 
          * 
          * <p> The number of bytes actually written at the target address maybe 
          * determined by consulting {@link #addressSize}. 
          * 
          * @see #getAddress(long) 
          */  
         public native void putAddress(long address, long x);  
       
         /// wrappers for malloc, realloc, free:  
       
         /** 
          * Allocates a new block of native memory, of the given size in bytes.  The 
          * contents of the memory are uninitialized; they will generally be 
          * garbage.  The resulting native pointer will never be zero, and will be 
          * aligned for all value types.  Dispose of this memory by calling {@link 
          * #freeMemory}, or resize it with {@link #reallocateMemory}. 
          * 
          * @throws IllegalArgumentException if the size is negative or too large 
          *         for the native size_t type 
          * 
          * @throws OutOfMemoryError if the allocation is refused by the system 
          * 
          * @see #getByte(long) 
          * @see #putByte(long, byte) 
          */  
         public native long allocateMemory(long bytes);  
1. long allocateMemory(long bytes) 
申请分配内存 
2. long getAddress(long address) 和void putAddress(long address, long x) 

对直接内存进行读写。

因为Unsafe这个类的访问是受限的,只有rt.jar中的类才能使用Unsafe的功能,它的构造方法是私有的,所以,我们不能通过new来创建实例。但是,可以通过反射的方法来获取Unsafe实例。 

下面就是一个直接访问内存的一个例子: 

import java.lang.reflect.Field;  
  
import sun.misc.Unsafe;  
  
public class DirectMemoryAccess {  
  
    public static void main(String[] args) {  
  
        /* 
         * Unsafe的构造函数是私有的,不能通过new来获得实例。 
         *  
         *  通过反射来获取 
         */  
        Unsafe unsafe = null;  
        Field field = null;  
        try {  
            field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");  
            /* 
             * private static final Unsafe theUnsafe = new Unsafe(); 
             *  
             * 因为field的修饰符为 private static final, 
             * 需要将setAccessible设置成true,否则会报java.lang.IllegalAccessException 
             */  
            field.setAccessible(true);  
            unsafe = (Unsafe) field.get(null);  
        } catch (SecurityException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (NoSuchFieldException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IllegalArgumentException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IllegalAccessException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
  
        long oneHundred = 100;  
        byte size = 1;  
  
        /* 
         * 调用allocateMemory分配内存 
         */  
        long memoryAddress = unsafe.allocateMemory(size);  
  
        /* 
         * 将100写入到内存中 
         */  
        unsafe.putAddress(memoryAddress, oneHundred);  
  
        /* 
         * 内存中读取数据  
         */  
        long readValue = unsafe.getAddress(memoryAddress);  
  
        System.out.println("Val : " + readValue);  
    }  
}  
输出结果: 
Val : 100 

如果,想要查阅Unsafe的源代码,请参考下面的链接. 

http://www.docjar.com/html/api/sun/misc/Unsafe.java.html

谢谢大家阅读!水平一般,能力有限!


猜你喜欢

转载自blog.csdn.net/zhuhaonan0929/article/details/79976523
今日推荐