Why there is no direct access to memory locations such as pointers in Java?

This question already has an answer here:

  • Does java really have pointers or not? [closed] 9 answers

  • You already mentioned the security reason yourself. Java program runs in container named Java Virtual Machine (JVM) that controls the memory management. This means that program cannot directly access memory for security and stability reasons: java program cannot damage memory of other process.

    Other reason is garbage collections. Like C++ Java has new keyword that allocates memory for new object. However java does not have delete . The removing of object that cannot be used any more is done automatically by GC. I guess it is a good reason to avoid direct memory access.

    BTW even if you are using pointers in C program you cannot easily access whole memory available for operating system. The pointers a localized for your memory space allocated for your process by OS.

    Next comment is about direct access to memory in java. You have 2 ways to do this: JNI/JNA that integrates java and native code and sun.misc.Unsafe that allows access to memory outside the JVM managed heap.

    And the last comment or even question: why do you need to access the memory directly?


    A design goal of JVM is to prevent all sorts of memory corruption introduced by pointer manipulation mistakes (programming mistakes).

    Manual memory management is supported by Java but in very limited ways:

  • Manipulation of byte memory buffers (safe)
  • Direct memory manipulation (unsafe)
  • Check out the following Javadocs:

    http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html http://www.docjar.com/docs/api/sun/misc/Unsafe.html

    链接地址: http://www.djcxy.com/p/5418.html

    上一篇: 为什么Swift在这个图像处理测试中比C慢100倍?

    下一篇: 为什么没有直接访问内存位置,比如Java中的指针?