[Java] Memory structure of JVM & Argument types

조현호_ChoHyeonHo·2024년 12월 31일

JVM structure

Figure: Memory Structure of JVM

Method area

When a certain class has materialized, JVM reads the class file(*.class) and saves the class data on here.

Heap

The area where instance is instantiated. Instance variables are instantiated here.

Class Var v Instance Var

CVIV
DeclarationDeclared with the static keyword inside a class but outside any method, constructor, or block.Declared inside a class but outside any method, constructor, or block.
AccessAccessed using the class name or object reference.They are accessed using the object reference.
SummaryClass variables (static variables) are shared among all instances of the class and are accessed using the class name or object reference.Instance variables are specific to each object and are not shared among objects.

Call Stack(=Execution stack)

Provides memory for the tasks of the methods.

About

각 메서드를 위한 메모리상의 작업공간은 서로 구별되며, 첫 번째로 호출된 메서드를 위한 작업공간이 호출스택의 맨 밑에 마련되고, 첫 번째 메서드 수행 중에 다른 메서드를 호출하게 되면, 첫 번째 메서드의 바로 위에 두 번째로 호출된 메서드를 위한 공간이 마련된다.
이 때 첫 번째 메서드는 수행을 멈추고, 두 번째 메서드가 수행되기 시작한다. 두 번째로 호출된 메서드가 수행을 마치게 되면, 두 번째 메서드를 위해 제공되었던 호출스택의 메모리공간이 반환되며, 첫 번째 메서드는 다시 수행을 계속하게 된다. 첫 번째 메서드가 수행을 마치면, 역시 제공되었던 메모리 공간이 호출스택에서 제거되며 호출스택은 완전히 비워지게 된다. 호출스택의 제일 상위에 위치하는 메서드가 현재 실행 중인 메서드이며, 나머지는 대기상태에 있게 된다.
따라서 호출스택을 조사해보면 메서드 간의 호출관계와 현재 수행중인 메서드가 어느 것인지 알 수 있다.

Arguments: Primitives v References

primitive typereference type
primitive vars are copied and passed to the methodsaddress of the instances are copied and passed to the methods
valid manipulationread onlyread & write
why?the method can only have the copy of valuethe method has the reference so it can access the storage directly via it.

Argument variables of the methods are a basically the copies of the values or the references of it. right?
Yes, in Java, the way arguments are passed to methods depends on whether the arguments are primitive types or reference types:

Code: ParameterTest.java

class Data{ int x;}
public class ParameterTest {
    public static void main(String[] args) {
        Data d = new Data();
        d.x = 10;
        System.out.println("main(): x = " + d.x);

        change(d);
        System.out.println("After change(d)");
        System.out.println("main(): x = " + d.x);
        
        change(d.x);
        System.out.println("After change(i)");
        System.out.println("main(): x = " + d.x);

    }

    static void change(Data d){
        d.x = 1000;
        System.out.println("change(): x = " + d.x);
    }
    static void change(int i){
        i = 2000;
        System.out.println("change(): x = " + i);
    }
}

Result

main(): x = 10
change(): x = 1000
After change(d) // original value has changed.
main(): x = 1000
change(): x = 2000
After change(i) // copied value has changed.
main(): x = 1000

Be aware of what is given to the method! Value itself? Or, address of the value?

profile
Behold the rabbit hole

0개의 댓글