[Java] static과 메모리

zerokick·2023년 7월 31일
0

Java

목록 보기
12/12
post-thumbnail

static과 메모리


메인 클래스의 동작 원리

  1. JVM(Java Virtual Machine)이 실행할 클래스를 찾는다.
  2. static 키워드가 붙은 멤버들을 static 메모리 영역에 자동으로 한 번 로딩한다.
    • static 멤버들은 클래스를 사용하는 시점에 딱 한 번만 메모리에 로딩된다.
    • main() 메서드의 경우 static이므로 메모리에 로딩된다.
  3. JVM이 static 메모리 영역에서 main() 메서드를 호출한다.
  4. 호출한 메서드를 Call static Frame Area(Stack Area)에 push한 뒤 동작을 시작한다.

JVM의 Memory Model

  1. Method Area
  • 메서드의 기계어코드가 할당되는 메모리 공간
  • static-zone, none-static-zone으로 나뉨
  1. Heap Area
  • 객체가 생성되는 메모리 공간
  • Garbage Collector에 의해서 더 이상 사용되지 않는 객체들이 관리됨
  1. Stack Area (Call Stack Frame Area)
  • 메서드 호출 시 기계어코드를 할당받아 메서드가 실행되는 메모리 공간
  • Program Counter에 의해 현재 실행중인 프로그램의 위치를 관리
  • LIFO 구조
  1. Runtime Constant Pool (Literal Pool)
  • 상수 값이 할당되는 메모리 공간
  • 문자열 상수가 할당되는 메모리 공간

static의 객체 생성

  • static 멤버의 경우 객체 생성 없이 호출하는 것이 바람직하다.
  • 객체 생성을 하지 못하도록 막는 방법
    : 접근제어자를 이용하여 생성자 메서드에 접근하지 못하도록한다.
public class AllStaticTest {
    public static void main(String[] args) {
        int a = 3;
        int b = 4;

//        AllStatic as = new AllStatic(); // 에러 발생

        System.out.println(AllStatic.sum(a, b));
        System.out.println(AllStatic.max(a, b));
        System.out.println(AllStatic.min(a, b));
    }
}
public class AllStatic {
    // 생성자 메서드에 접근하지 못하도록
    // 접근제어자를 private으로 설정
    private AllStatic() {

    }

    public static int sum(int x, int y) {
        return x + y;
    }

    public static int max(int x, int y) {
        return x > y ? x : y;
    }

    public static int min(int x, int y) {
        return x > y ? y : x;
    }
}

Class, Object, Instance

  1. Class
  • 객체 모델링 도구 (설계도)
public class Student {
	private String name;
    private int age;
    private String grade;
}
  1. Object
  • 클래스를 통해 선언되는 변수
Student st;
  • 아직 변수가 구체적인 실체를 가리키지 않고 있는 상태
  1. Instance
  • 객체가 실제로 생성되어 Heap Memory에 만들어진 상태
st = new Student();
  • 변수가 구체적인 실체를 가리키고 있는 상태
profile
Opportunities are never lost. The other fellow takes those you miss.

1개의 댓글

comment-user-thumbnail
2023년 7월 31일

좋은 정보 얻어갑니다, 감사합니다.

답글 달기