ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 메모리 주소만으로 Heap의 인스턴스에 접근할 수 있을까?
    Java/Basics 2020. 6. 17. 00:32


    자바 스터디를 하던 중, 


    메모리 주소만으로 Heap의 인스턴스에 접근할 수 있을까?


    라는 질문이 나와서 이에 대해 알아봤다. 결론은 접근할 수 없다 왜 그런지 살펴보자




    ■개발자는 객체의 주소를 직접적으로 지정할 수 없다


    개발자는 객체의 주소를 직접적으로 지정할 수 없다. 오직 간접적으로만 할 수 있다.


    예를들어, String str = "hello"; 코드를 보면 "hello" 문자열의 메모리 주소가 


    str에 할당되고 있다. 이제 str은 메모리 주소를 갖게 된다. 그리고 String str2 = str; 


    코드를 보면 str이 가리키고 있는 주소가 str2에 할당되고 있다. "hello"라는 인스턴스를 


    복사하는 것이 아닌 "hello"주소를 복사하여 할당하는 것이다. 


    그러나 메모리 주소를 참조 변수에 직접 할당할 수는 없다. 


    왜냐하면 실제 주소를 알 수 없기 때문이다.


    JVM만이 객체가 메모리에 저장되어 있는 위치를 알고 있으며, 할당 작업을 실행하는 


    동안 해당 주소를 변수에 할당한다. 참조 변수에 직접 지정할 수 있는 주소는 null 뿐이다.


    원문


    You cannot assign the address of an object directly. You can only do so indirectly.

    For example, in statement the 'String str = "hello";' you are assigning the address of the memory location at which the string "hello" is stores to str variable.

    str, therefore, now contains the address of a memory location.


    Similarly, in statement 'String str2 = str;' you are assigning the value stored in str to str2.

    You are not copying "hello" to str2.

    You are just copying the address stored in str to str2.


    You cannot assign a memory address to a reference variable directly because you don't know the actual address.

    Only the JVM knows where an object is stored in memory and it assigns that address to the variable while executing the assignment operation.

    The only "address" you can assign to a reference variable directly is null.


    그렇다면 궁금증이 하나 더 생긴다.


    왜 JVM만이 객체가 메모리에 저장되어 있는 위치를 알 수 있을까?




    ■JVM만이 객체가 메모리에 저장되어 있는 위치를 아는 이유


    자바에선 변수의 메모리 주소를 얻는 것은 무의미하다.


    왜냐하면 JVM은 자유롭게 객체를 구현하고, GC를 이용해 그 객체의 위치를 


    이동시키기 때문이다. JVM만이 정확한 메모리 주소를 알고있다.


    원문

    Getting the memory addresses of variables is meaningless within Java, since the JVM is at liberty to implement objects and move them as it seems fit (your objects may/will move around during garbage collection etc.)

    'Java > Basics' 카테고리의 다른 글

    Java Thread(with Multi Thread)  (0) 2020.06.21
    같은 value 값을 가지는 String들의 hashcode가 같은 이유  (0) 2020.06.19
    Java Heap Dump  (0) 2020.06.15
    JVM, JRE, JDK  (0) 2020.06.14
    Java Heap (with GC)  (0) 2020.06.08

    댓글

Designed by Tistory.