❓
물음표살인마 블로그
  • README
  • ALGORITHM
    • Sieve of Eratosthenes
    • Round Up
    • Binary Search
    • Union Find
    • Sorting Array
    • Lcm, Gcd
  • TechTalk Review
    • Template
  • Books
    • CS Note for Interview
      • Ch1. Design Pattern & Programming paradigm
        • 1.1.1 Singleton Pattern
        • 1.1.2 Factory Pattern
        • 1.1.4 Observer Pattern
        • 1.1.5 Proxty Pattern & Proxy Server
        • 1.1.8 Model-View-Controller Pattern
        • 1.2.1 Declarative and Functional Programming
        • 1.2.2 Object Oriented Programming
      • Ch2. Network
        • 2.2.1 TCP/IP Four-Layer Model
        • 2.2.1-1 TCP 3, 4 way handshake
        • 2.3 Network Devices L4, L7
        • 2.4.1 ARP, RARP
        • 2.4.2 Hop By Hop Communication
        • 2.4.3 IP Addressing Scheme
      • Ch3. Operating System
        • 3.1.1 Roles and Structure of Operating Systems
        • 3.2.1 Memory Hierarchy
        • 3.2.2 Memory Management
        • 3.3.1 Processes and Compilation Process
        • 3.3.3 Memory Structure of a Process
        • 3.3.4 Process Control Block (PCB)
        • 3.3.5 Multiprocessing
        • 3.3.6 Threads and Multithreading
        • 3.3.7 Shared Resources and Critical Sections
        • 3.3.8 Deadlock
        • 3.4 CPU Scheduling Algorithm
      • Ch4. Database
        • 4.1 Database Basic
        • 4.2 Normalization
        • 4.3 Transaction and Integrity
        • 4.4 Types of Databases
        • 4.5 Indexes
        • 4.6 Types of Joins
        • 4.7 Principles of Joins
      • Ch5. Data Structure
    • Learning the Basics of Large-Scale System Design through Virtual Interview Cases
      • 1. Scalability based on user counts(1/2)
      • 1. Scalability based on user counts(2/2)
      • 2.Back-of-the-envelope estimation
      • 3. Strategies for System Design Interviews
      • 4. Rate Limiter
      • 5. Consistent Hashing
      • 6. Key-Value System Design
      • 7. Designing a Unique ID Generator for Distributed Systems
      • 8. Designing a URL Shortener
      • 9. Designing a Web Crawler
      • 10. Notification System Design
      • 11. Designing a News Feed System
      • 12. Chat System Design
      • 13. AutoComplete
      • 14. Design YouTube
      • 15. Design Google Drive
      • Loadbalancer Algorithms
      • Cache tier
      • CDN, Content Delivery Network
      • Stateless Web tier
    • Computer System A programmer's perspective
    • Effective Java
      • Item 1. Consider Static Factory Methods Instead of Constructors
      • Item 2. Consider a Builder When Faced with Many Constructor Parameters
      • Item 3. Ensure Singleton with Private Constructor or Enum Type
      • Item 4. Enforce Noninstantiability with a Private Constructor
      • Item 5. Prefer Dependency Injection to Hardwiring Resources
      • Item 6. Avoid Creating Unnecessary Objects
      • Item 7. Eliminate Obsolete Object References
      • Item 8. Avoid Finalizers and Cleaners
      • Item 9.Prefer try-with-resources to try-finally
      • Item10. Adhering to General Rules When Overriding equals
        • Handling Transitivity Issues
        • Ensuring Consistency
      • Item11. Override hashCode When You Override equals
      • Item12. Always Override toString
        • Always Override toString
      • Item13. Override Clone Judiciously
      • Item14. Consider Implementing Comparable
      • Item15. Minimize the Accessibility of Classes and Members
      • Item16. Accessor Methods Over Public Fields
      • Item17. Minimize Mutability
      • Item18. Composition over inherentance
      • Item19. Design and Document for Inheritance, or Else Prohibit It
      • Item20. Prefer Interfaces to Abstract Classes
      • Item21. Design Interfaces with Implementations in Mind
      • Item22. Use Interfaces Only to define Types
      • Item23. Prefer Class Hierarchies to Tagged Classes
      • Item24. Favor Static Member Classes Over Non-Static
      • Item28. Use Lists Instead of Arrays
      • Item29. Prefer Generic Types
      • Item30. Favor Generic Methods
    • Head First Design Patterns
      • Ch1. Strategy Pattern
      • Ch2. Observer Pattern
        • Ver1. Ch2. Observer Pattern
      • Ch3. Decorator Pattern
        • Ch3. Decorator Pattern
      • Ch4. Factory Pattern
      • Ch5. Singleton Pattern
      • Ch6. Command Pattern
      • Ch7. Adapter and Facade Pattern
      • Ch8. Template Method Pattern
    • Digging Deep into JVM
      • Chapter 2. Java Memory Area & Memory Overflow
      • Chapter 3. Garbage Collector & Memory Allocation Strategy (1/2)
      • Chapter 3. Garbage Collector & Memory Allocation Strategy (2/2)
      • Chapter 5. Optimization Practice
      • Chapter 6. Class file structure
      • Chapter 8. Bytecode Executor Engine (1/2)
  • Interview Practices
    • Restful API Practices
      • Url Shortener API
      • Event Ticket Reservation API
      • Course Management API
      • Search posts by tags API
      • Online Code platform API
      • Simple Task Management API
      • Event Participation API
      • Review System API
      • Car management API
      • Online Library
    • Tech Review
      • if(kakao)
        • Kakao Account Cache Migration / if(kakao)2022
        • Improving the Anomaly Detection System for KakaoTalk Messaging Metrics / if(kakao) 2022
        • Standardizing API Case Handling Without Redeployment / if(kakaoAI)2024
        • JVM warm up / if(kakao)2022
    • Naver Computer Science
      • Process & Thread
      • TCP & UDP
      • Spring & Servlet
      • Filter & Interceptor & AOP
      • Equals() & ==
      • Dependency Injection
      • Object Oriented Programming
  • F-Lab
    • Week1
      • Client & Server
      • HTTP
      • TCP/UDP
      • REST API
      • Questions
        • Object Oriented Programming
        • HTTP
        • Process & Thread
        • Data Structure
    • Week2
      • OSI 7 layer
      • Web vs WAS
    • Week3
      • RDB vs NoSQL
      • RDB Index
      • Cache
      • Redis
      • Messaging Queue
    • Week4
      • Project - Ecommerce
    • Week5
      • ERD - 1
    • Week6
      • Ecommerce - 2
      • Role
      • pw hashing && Salt
      • CreatedAt, ModifiedAt
      • JWT
      • Copy of ERD - 1
    • Week7
      • Vault (HashiCorp Vault)
    • Week 8
      • Api Endpoints
    • Week10
      • Product Create Workflow
  • TOY Project
    • CodeMentor
      • Implementation of Kafka
      • Project Improvement (Architectural Enhancements)
      • Communication between servers in msa
  • JAVA
    • MESI protocol in CAS
    • CAS (Compare and Set)
    • BlockingQueue
    • Producer & Consumer
    • Synchronized && ReentrantLock
    • Memory Visibility
    • Checked vs Unchecked Exception
    • Thread
    • Batch delete instead of Cascade
    • Java Questions
      • Week 1(1/2) - Basic Java
      • Week 1(2/2) - OOP
      • Week 2(1/2) - String, Exception, Generic
      • Week2(2/2) Lambda, Stream, Annotation, Reflection
      • Week3(1/2) Collections
      • Week3(2/2) Threads
      • Week4 Java Concurrency Programming
      • Week5 JVM & GC
    • Java 101
      • JVM Structure
      • Java Compiles and Execution Method
      • Override, Overload
      • Interface vs Abstract Class
      • Primitive vs Object Type
      • Identity and equality
      • String, StringBuilder, StringBuffer
      • Checked Exceptions and Unchecked Exceptions
      • Java 8 methods
      • Try-with-reources
      • Strong Coupling and Loose Coupling
      • Serialization and Deserialization
      • Concurrency Programming in Java
      • Mutable vs Immutable
      • JDK vs JRE
  • SPRING
    • DIP. Dependency Inversion Principal
    • Ioc container, di practice
    • @Transactional
    • Proxy Pattern
    • Strategy Pattern
    • Template Method Pattern
    • using profile name as variable
    • Spring Questions
      • Spring Framework
      • Spring MVC & Web Request
      • AOP (Aspect-Oriented Programming)
      • Spring Boot
      • ORM & Data Access
      • Security
      • ETC
  • DATABASE
    • Enhancing Query Performance & Stability - User list
    • Ensuring Data Consistency, Atomicity and UX Optimization (feat.Firebase)
    • Redis: Remote Dictionary Server
    • Database Questions
      • Week1 DBMS, RDBMS basics
      • Week2 SQL
      • Week3 Index
      • Week4 Anomaly, Functional Dependency, Normalization
      • Week5 DB Transaction, Recovery
    • Normalization
      • 1st Normal Form
      • 2nd Normal Form
      • 3rd Normal Form
  • NETWORK
    • HTTP & TCP head of line blocking
    • HTTP 0.9-3.0
    • Blocking, NonBlocking and Sync, Async
    • Network Questions
      • Week1 Computer Network Basic
      • Week2(1/3) Application Layer Protocol - HTTP
      • Week2(2/3) Application Layer Protocol - HTTPS
      • Week2(3/3) Application Layer Protocol - DNS
      • Week3 Application Layer
      • Week4 Transport Layer - UDP, TCP
      • Week5 Network Layer - IP Protocol
    • Network 101
      • https://www.google.com
      • TCP vs UDP
      • Http vs Https
      • TLS Handshake 1.2
      • HTTP Method
      • CORS & SOP
      • Web Server Software
  • OS
    • Operating System Questions
      • Week1 OS & How Computer Systems Work
      • Week2(1/2) Process
      • Week2(2/2) Thread
      • Week3 CPU Scheduling
      • Week4 Process Synchronize
      • Week5 Virtual Memory
    • Operating System 101
      • Operating system
        • The role of the operating system
        • The composition of the operating system.
      • Process
        • In Linux, are all processes except the initial process child processes?
        • Zombie process, orphan process
        • (Linux) Daemon process
        • Process address space
        • Where are uninitialized variables stored?
        • Determination of the size of the Stack and Heap
        • Access speed of Stack vs Heap
        • Reason for memory space partitioning
        • Process of compiling a process
        • sudo kill -9 $CURRENT_PID
      • Thread
        • Composition of a thread's address space
      • Process vs Thread
        • Creation of processes and threads in Linux
      • Multiprocessing
        • Web Browser
        • Implementation of multiprocessing
        • Application areas of multiprocessing
      • Multithreading
        • Application areas of multithreading
      • Interrupt
        • HW / SW Interrupt
        • Method of handling interrupts
        • Occurrence of two or more interrupts simultaneously
      • Polling
      • Dual Mode
        • Reason for distinguishing between user mode and kernel mode
      • System call
        • Differentiation between system calls
        • Types of system calls
        • Execution process of a system call
      • Process Control Block (PCB)
        • PCB의 구조
        • 쓰레드는 PCB를 갖고 있을까?
        • 프로세스 메모리 구조
      • Context switching
        • Timing of context switching
        • Registers saved during context switching
        • Context switching in processes
        • Context switching in threads
        • Difference between context switching in processes and threads
        • Information of the current process during context switching
      • Interprocess Communication (IPC)
        • Cases where IPC is used
        • Process address space in IPC Shared Memory technique
        • Types of IPC
  • COMPUTER SCIENCE
    • Computer Architecture 101
      • 3 components of a computer
      • RAM vs ROM
      • CPU vs GPU
      • SIMD
      • Two's complement
      • Harvard Architecture vs. von Neumann Architecture
      • The structure of a CPU.
      • Instruction cycle (CPU operation method)
      • Instruction pipelining
      • Bus
      • Memory area
      • Memory hierarchy structure
        • Reason for using memory hierarchy structure
      • Cache memory
      • L1, L2, L3 Cache
      • Locality of reference (cache)
      • Fixed-point vs Floating-point
        • epresentation of infinity and NaN (Not a Number) in floating-point
      • RISC vs CISC
      • Hamming code
      • Compiler
      • Linking
      • Compiler vs Interpreter
      • Mutex vs Semaphore
      • 32bit CPU and 64bit CPU
      • Local vs Static Variable
      • Page
  • Programming Paradigm
    • Declarative vs Imperative
  • JPA, QueryDsl
    • why fetchResults() is deprecated
  • PYTHON
    • Icecream
  • FASTAPI
    • Template Page
  • LINUX
    • Template Page
  • DATA STRUCTURE
    • Counting Sort
    • Array vs Linked List
  • GIT, Github
    • git clone, invalid path error
  • INFRA
    • Template Page
  • AWS
    • Server Log Archive Pipeline
    • Image Processing using Lambda
  • DOCKER
    • Docker and VM
    • Python Executable Environment
    • Docker commands
  • docker-compose
    • Kafka, Multi Broker
  • KUBERNATES
    • !Encountered Errors
      • my-sql restarts
      • kafka producer: disconnected
    • Kubernetes Components
    • Helm
      • Helm commands
    • Pod network
    • Service network
      • deployment.yaml
      • services.yaml
    • Service type
      • Cluster IP
      • NodePort
    • service-name-headless?
    • kube-proxy
  • GraphQL
    • Template Page
  • WEB
    • Template Page
  • Reviews
    • Graphic Intern Review
    • Kakao Brain Pathfinder Review
    • JSCODE 자바 1기 Review
  • 😁Dev Jokes
    • Image
      • Plot twist
      • Priorities
      • SQL join guide
      • Google is generous
      • Genie dislikes cloud
      • buggy bugs
      • last day of unpaid internship
      • what if clients know how to inspect
      • its just game
      • how i wrote my achievement on resume
      • self explanatory
      • chr(sum(range(ord(min(str(not))))))
Powered by GitBook
On this page
  • 1. 소스 코드 작성
  • 2. 자바 컴파일러 - 컴파일
  • 파싱
  • 의미 분석
  • 중간 코드 생성
  • 최적화
  • 바이트 코드 생성
  • 3. 클래스 로더 - 클래스 로딩
  • 4. 실행 엔진 - 바이트 코드 실행
  • 5. 가비지 컬렉터 - 실행중 메모리 관리
  • 5-1. 런타임 데이터 영역
  • 6. 네이티브 메서드 실행
  • 7. 프로그램 종료
  1. JAVA
  2. Java 101

Java Compiles and Execution Method

Java의 컴파일과 실행 방식

Compiler vs JVM

컴파일러 (Compiler)

Compiler

컴파일러는 소스 코드를 바이트코드로 변환하는 프로그램입니다. 자바에서 사용되는 컴파일러는 javac로, 자바 소스 파일(.java)을 컴파일하여 바이트코드(.class 파일)로 변환합니다.

주요 기능

  1. 파싱(Parsing): 소스 코드를 읽고 문법적으로 분석하여 구문 트리(Syntax Tree)로 변환합니다. 문법 오류를 검출할 수 있습니다.

  2. 의미 분석(Semantic Analysis): 변수 선언, 타입 검사, 메서드 호출 등이 올바른지 확인합니다. 의미론적 오류를 검출할 수 있습니다.

  3. 중간 표현 생성(Intermediate Representation Generation): 소스 코드의 구조를 중간 표현으로 변환합니다.

  4. 최적화(Optimization): 중간 표현을 기반으로 성능을 향상시키기 위해 다양한 최적화를 수행합니다.

  5. 바이트코드 생성(Bytecode Generation): 최적화된 중간 표현을 바이트코드로 변환하여 .class 파일로 저장합니다.

컴파일러의 특징

  • 언어 특정적: 자바 컴파일러는 자바 소스 코드를 바이트코드로 변환하는 데 특화되어 있습니다.

  • 정적 분석: 컴파일 타임에 코드의 문법과 의미를 분석하여 오류를 검출합니다.

  • 플랫폼 독립적 바이트코드 생성: 컴파일러는 자바 소스 코드를 플랫폼에 독립적인 바이트코드로 변환합니다.


JVM (Java Virtual Machine)

Java Virtual Machine

JVM은 자바 바이트코드를 실행하는 가상 머신입니다. JVM은 바이트코드를 해석하고 실행하며, 메모리 관리, 가비지 컬렉션, 스레드 관리 등의 기능을 제공합니다.

주요 기능

  1. 클래스 로딩(Class Loading): 바이트코드(.class 파일)를 메모리에 로드합니다.

  2. 바이트코드 검증(Bytecode Verification): 클래스 파일의 형식과 구조가 JVM 명세를 준수하는지 확인합니다.

  3. 실행(Execution): 바이트코드를 해석하고 실행합니다. 인터프리터와 JIT 컴파일러를 통해 실행됩니다.

  4. 메모리 관리(Memory Management): JVM은 힙, 스택, 메소드 영역 등을 관리합니다.

  5. 가비지 컬렉션(Garbage Collection): 더 이상 사용되지 않는 객체를 자동으로 메모리에서 제거합니다.

  6. 네이티브 메서드 실행(Native Method Execution): JNI를 통해 네이티브 메서드를 호출하고 실행합니다.

JVM의 특징

  • 플랫폼 독립성: JVM은 한 번 작성된 자바 프로그램을 다양한 플랫폼에서 실행할 수 있게 합니다. 바이트코드는 플랫폼 독립적이지만, JVM은 각 플랫폼에 맞게 구현됩니다.

  • 동적 실행: JVM은 런타임에 바이트코드를 해석하고 실행합니다. JIT 컴파일러를 통해 반복적으로 실행되는 바이트코드를 네이티브 코드로 변환하여 성능을 최적화합니다.

  • 메모리 관리 및 가비지 컬렉션: JVM은 메모리를 효율적으로 관리하고, 가비지 컬렉션을 통해 메모리 누수를 방지합니다.

컴파일러와 JVM의 비교

구분
컴파일러 (Compiler)
JVM (Java Virtual Machine)

역할

소스 코드를 바이트코드로 변환

바이트코드를 실행

입력

자바 소스 파일(.java)

바이트코드(.class)

출력

바이트코드(.class)

프로그램 실행 결과

주요 기능

구문 분석, 의미 분석, 최적화, 바이트코드 생성

클래스 로딩, 바이트코드 검증, 실행, 메모리 관리, 가비지 컬렉션

실행 시점

컴파일 타임

런타임

플랫폼 독립성

바이트코드 생성

플랫폼 독립적인 바이트코드를 실행, JVM은 플랫폼에 맞게 구현

성능 최적화

컴파일 타임 최적화

JIT 컴파일러를 통한 런타임 최적화

1. 소스 코드 작성

자바 소스 코드를 작성한 후, javac 컴파일러를 사용하여 자바 바이트코드(.class 파일)로 컴파일합니다. 이 과정에서 자바 소스 코드는 JVM이 이해할 수 있는 바이트코드로 변환됩니다. 예를 들어, HelloWorld.java 파일을 작성.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

2. 자바 컴파일러 - 컴파일

파싱

컴파일러는 소스 코드를 읽고, 이를 문법적으로 분석하여 구문트리(Syntax Tree)로 변환합니다. 이 단계에서 문법 오류를 검출합니다

의미 분석

구문 트리를 기반으로 의미 분석을 수행합니다. 변수 선언, 타입 검사, 메서드 호출 등이 올바른지 확인합니다.

중간 코드 생성

중간 코드는 JVM이 이해할 수 있는 명령어 집합으로, 플랫폼 독립적입니다.

최적화

중간 코드 생성 후, 컴파일러는 바이트코드를 최적화합니다. 중복 코드 제거, 루프 최적화를 합니다

바이트 코드 생성

최적화된 중간 코드는 바이트 코드로 변환되어 .class 파일로 저장됩니다. \

javac HelloWorld.java -> HelloWord.class 생성

이 명령을 실행하면 HelloWorld.class 파일이 생성됩니다. 컴파일된 바이트코드는 JVM에서 실행될 준비가 됩니다.

3. 클래스 로더 - 클래스 로딩

JVM의 클래스 로더가 .class 파일을 로드하고, 런타임 데이터 영역(Runtime Data Area)으로 배치합니다. 이 과정에서 필요에 따라 다른 클래스를 로드하거나 링크합니다. 클래스 로딩은 세 단계로 이루어집니다.

  • 로딩(Loading): 클래스 파일을 읽고 메모리에 적재합니다.

  • 링킹(Linking): 클래스 파일의 참조를 확인하고, 기본 초기화를 수행합니다.

    • 검증(Verification): 클래스 파일의 형식과 구조가 JVM 명세를 준수하는지 확인합니다. 바이트코드 검증기를 통해 바이트코드의 무결성을 확인합니다.

    • 준비(Preparation): 클래스가 필요로 하는 메모리를 할당한다.

    • 해결(Resolution): 상수 풀(Constant Pool)에 있는 심볼릭 레퍼런스를 직접 참조로 변경합니다.

  • 초기화(Initialization): 클래스 초기화 블록(static {})을 실행하고, 정적 변수들을 적절한 값으로 초기화 (static 필드들을 설정된 값으로 초기화 등)

4. 실행 엔진 - 바이트 코드 실행

실행 엔진이 바이트코드를 해석하여 실행합니다. 실행 방식은 인터프리터와 JIT 컴파일러를 통해 이루어집니다.

  • 인터프리터(Interpreter): 바이트코드를 한 줄씩 읽어 실행합니다. 인터프리터는 프로그램의 초기 시작 속도가 빠르지만, 반복되는 코드를 실행할 때는 비효율적입니다.

  • JIT 컴파일러(Just-In-Time Compiler): 반복적으로 실행되는 바이트코드를 머신 코드로 변환하여 캐싱합니다. 이를 통해 실행 속도를 크게 향상시킬 수 있습니다. JIT 컴파일러는 실행 중에 바이트코드의 핫스팟(반복 실행되는 부분)을 찾아 네이티브 코드로 변환합니다. 이렇게 변환된 네이티브 코드는 캐시에 저장되어 이후에 빠르게 실행됩니다.

5. 가비지 컬렉터 - 실행중 메모리 관리

JVM은 실행 중에 메모리를 효율적으로 관리합니다. JVM의 가비지 컬렉터(Garbage Collector)가 주기적으로 힙 메모리를 검사하여 더 이상 참조되지 않는 객체를 제거합니다. 가비지 컬렉션은 크게 다음과 같은 단계로 이루어집니다:

  • 마킹(Marking): 사용 중인 객체와 사용되지 않는 객체를 식별합니다.

  • 정리(Sweeping): 사용되지 않는 객체를 메모리에서 제거합니다.

  • 압축(Compaction): 메모리 단편화를 방지하기 위해 객체들을 한 곳으로 모읍니다.

가비지 컬렉션의 주기와 방식은 JVM의 구현에 따라 다를 수 있으며, 다양한 알고리즘이 사용됩니다. 주요 가비지 컬렉션 알고리즘에는 마크-스위프(Mark-and-Sweep), 마크-컴팩트(Mark-and-Compact), 복사(Copying) 등이 있습니다.

5-1. 런타임 데이터 영역

런타임 데이터 영역은 JVM의 메모리 영역으로, 자바 애플리케이션을 실행할 때 사용되는 데이터들을 적재하는 영역.

  • 메소드 영역: 클래스 메타데이터, 상수, 스태틱 변수 등을 저장합니다.

  • 힙: 모든 객체 인스턴스와 배열을 저장합니다

  • 스택: 각 스레드마다 별도로 생성되며, 메서드 호출 시 생성되는 프레임을 저장합니다.

  • PC 레지스터: 현재 실행 중인 JVM 명령어의 주소를 가리킵니다. CPU 명령어(Instruction)을 수행하면서 필요한 정보를 CPU내 레지스터에 저장.

  • 네이티브 메서드 스택: 네이티브 메서드 호출 시 사용되는 스택입니다.

메소드 영역, 힙 영역은 모든 쓰레드가 공유한다. 스택 영역, PC 레지스터, 네이티브 메서드 스택은 쓰레드마다 생성되는 개별 영역.

5-2. 메서드 영역

JVM이 시작될 때 생성되는 공간으로, 바이트 코드(.class)를 처음 메모리 공간에 올릴 때 초기화되는 대상을 저장하기 위한 메모리 공간. JVM이 동작하고 클래스가 로드될때 적재되서 프로그램이 종료될 때까지 저장. 쉽게 말해, 정적 필드와, 클래스 구조만을 갖고 있다.

  • Runtime Constant Pool: 메소드 영역안에 존재하는 별도의 관리영역으로, 클래스 생성할때 참조해야할 정보들을 상수로 가지고 있는 영역. JVM은 이를 통해 해당 메소드나 필드의 실제 메모리 상 주소를 찾아 참조.

  • Field Info: 멤버 변수의 이름, 데이터 타입, 접근 제어자의 정보

  • Method Info: 메소드 이름, return 타입, 함수 매개변수, 접근 제어자의 정보

  • Type Info: Class / Interface 인지 여부 저장, Type의 속성, 이름 / Super Class의 이름

5-3. 힙 영역

JVM이 관리하는 프로그램 상에서 데이터를 저장하기 위해 런타임 시 동적으로 할당하여 사용하는 영역. new 연산자로 생성되는 클래스와 인스턴스 변수, 배열 타입 등 Reference Type이 저장되는 영역,

Rreference Type으로, JVM 스택 영역의 변수나 다른 객체의 필드에서 참조. 힙의 참조 주소는 스택이 갖고 있고 해당 객체를 통해서만 힙 영역에 있는 인스턴스를 핸들링할 수 있는 것.

5-4. 스택 영역

int, long, boolean 등 primitive type 자료형을 생성할때 저장하는 공간으로, 임시적으로 사용되는 변수나 정보들이 저장되는 영역.

메서드 호출 시마다 각각의 스택 프레임(메서드만을 위한 공간)이 생성되고 메서드 안에서 사용되는 값들을 저장하고, 호출된 메서드의 매개변수, 지역변수, 리턴 값 및 연산 시 일어나는 값들을 임시로 저장. 메서드가 끝나면 프레임 별로 삭제. (LIFO)

예: Person p = new Person(); 클래스 생성시, new에 의해 생성된 클래스는 Heap에, 생성된 클래스의 참조인 p는 Stack에 저장.

6. 네이티브 메서드 실행

자바 애플리케이션이 JNI를 통해 네이티브 메서드를 호출할 때, JVM은 네이티브 메서드 스택과 네이티브 메서드 라이브러리를 사용합니다. 네이티브 메서드는 주로 성능 최적화나 하드웨어 접근을 위해 사용됩니다. 자바 코드가 네이티브 메서드를 호출하면, JVM은 네이티브 라이브러리를 로드하고 해당 메서드를 실행합니다. 네이티브 메서드 실행 후, 제어권은 다시 JVM으로 돌아옵니다.

7. 프로그램 종료

자바 애플리케이션이 종료될 때, JVM은 모든 리소스를 해제하고 종료 절차를 밟습니다. JVM은 종료 훅(Shutdown Hook)을 통해 애플리케이션 종료 시 수행할 작업을 정의할 수 있습니다. 종료 훅은 주로 리소스 정리, 로그 기록, 네트워크 연결 종료 등의 작업에 사용됩니다.

PreviousJVM StructureNextOverride, Overload

Last updated 9 months ago