❓
물음표살인마 블로그
  • 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
  • 11. 람다(Lambda)란 무엇인가요?
  • 12. 스트림(Stream)이란 무엇인가요?
  • 13. 람다와 스트림은 왜 생겨났을까요?
  • 14. 자바에서 어노테이션이란 무엇일까요?
  • 15. 어노테이션을 왜 사용할까요?
  • 16. 어노테이션은 리플렉션으로 동작한다고 말씀해 주셨는데, 리플렉션은 무엇인가요?
  • 17. 리플렉션을 활용해서 어노테이션의 메타 데이터를 가져오는 등의 로직을 실제로 구현해 보신 적이 있으신가요?
  • 18. System.out.println 클래스는 성능이 좋지 않다고 하는데 이유가 무엇일까요?
  1. JAVA
  2. Java Questions

Week2(2/2) Lambda, Stream, Annotation, Reflection

람다, 스트림, 어노테이션, 리플렉션

11. 람다(Lambda)란 무엇인가요?

11.1 람다의 정의

람다(Lambda)는 자바 8에서 도입된 함수형 프로그래밍 개념을 지원하는 표현식입니다. 람다는 익명 함수(이름이 없는 함수)를 간단하게 표현할 수 있게 해주며, 코드의 간결성을 높이고, 자바에서 함수형 인터페이스를 쉽게 구현할 수 있게 해줍니다.

11.2 람다의 기본 구조

람다 표현식의 기본 구조는 다음과 같습니다:

(parameters) -> expression

또는 블록이 필요한 경우:

(parameters) -> { statements; }

11.3 예시: Runnable 인터페이스 구현

람다를 사용하여 Runnable 인터페이스를 구현하는 예시입니다.

// 람다를 사용하지 않은 경우
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("Runnable 실행");
    }
};

// 람다 표현식을 사용한 경우
Runnable lambdaRunnable = () -> System.out.println("Runnable 실행");

위 예시에서 볼 수 있듯이, 람다 표현식을 사용하면 불필요한 코드가 줄어들고, 더 간결하게 코드를 작성할 수 있습니다.

11.4 람다의 장점

  • 코드 간결성: 람다를 사용하면 코드가 간결해져 가독성이 높아집니다.

  • 익명 함수 표현: 인터페이스의 단일 메서드를 간단하게 구현할 수 있습니다.

  • 지연 실행: 람다는 코드의 지연 실행을 지원하여 메모리 사용량을 줄일 수 있습니다.

12. 스트림(Stream)이란 무엇인가요?

12.1 스트림의 정의

스트림(Stream)은 자바 8에서 도입된 컬렉션 데이터의 반복, 필터링, 매핑 등의 작업을 선언적으로 처리할 수 있는 API입니다. 스트림을 사용하면 대량의 데이터를 처리하는 코드를 간결하고, 직관적으로 작성할 수 있습니다.

12.2 스트림의 주요 특징

  • 선언적 코드: 스트림은 데이터를 어떻게 처리할지를 선언적으로 표현합니다. 이는 코드의 가독성을 높입니다.

  • 중간 연산과 최종 연산: 스트림은 중간 연산(intermediate operation)과 최종 연산(terminal operation)으로 나뉩니다. 중간 연산은 스트림을 반환하며, 최종 연산은 결과를 반환하거나 스트림의 요소를 소비합니다.

  • 게으른 연산: 스트림은 필요할 때까지 계산을 지연시킵니다. 즉, 최종 연산이 호출될 때까지 중간 연산은 수행되지 않습니다.

  • 병렬 처리 지원: 스트림은 간단한 코드 수정만으로도 병렬 처리를 지원하여 성능을 최적화할 수 있습니다.

12.3 스트림의 예시

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// 필터링과 매핑을 통한 스트림 처리
List<String> result = names.stream()
                           .filter(name -> name.startsWith("A"))
                           .map(String::toUpperCase)
                           .collect(Collectors.toList());

위 코드에서 names.stream()을 통해 스트림을 생성하고, 필터링과 매핑 연산을 적용하여 원하는 결과를 얻을 수 있습니다.

12.4 스트림의 장점

  • 간결한 코드: 스트림을 사용하면 데이터 처리 로직을 간결하게 작성할 수 있습니다.

  • 유연한 데이터 처리: 다양한 중간 연산과 최종 연산을 조합하여 복잡한 데이터 처리도 쉽게 구현할 수 있습니다.

  • 병렬 처리: 대용량 데이터 처리 시 병렬 스트림을 사용하여 성능을 향상시킬 수 있습니다.

13. 람다와 스트림은 왜 생겨났을까요?

13.1 배경

람다와 스트림이 도입되기 전, 자바에서는 익명 클래스를 통해 함수형 인터페이스를 구현하거나 반복문을 사용하여 데이터를 처리해야 했습니다. 이러한 방식은 코드가 장황해지고, 반복적인 패턴이 발생하며, 코드의 가독성이 떨어지는 문제가 있었습니다.

13.2 람다의 필요성

람다는 익명 클래스의 장황한 구문을 간결하게 줄여주며, 함수형 인터페이스를 더 쉽게 구현할 수 있도록 도와줍니다. 이는 자바에서 함수형 프로그래밍을 지원하는 중요한 도구가 되었습니다.

13.3 스트림의 필요성

스트림은 대량의 데이터를 처리할 때 발생하는 반복적인 코드를 줄이고, 선언적으로 데이터를 처리할 수 있게 합니다. 또한, 스트림은 병렬 처리 기능을 지원하여, 멀티코어 환경에서의 성능 최적화를 가능하게 합니다.

13.4 순수 함수와 사이드 이펙트의 방지

람다와 스트림은 순수 함수(pure function)의 개념을 기반으로 합니다. 순수 함수는 동일한 입력에 대해 항상 동일한 출력을 반환하며, 외부 상태를 변경하지 않습니다. 이를 통해 코드의 예측 가능성을 높이고, 사이드 이펙트가 발생하지 않도록 보장합니다.

14. 자바에서 어노테이션이란 무엇일까요?

14.1 어노테이션의 정의

어노테이션(annotation)은 자바 소스 코드에 메타데이터를 제공하는 일종의 주석입니다. 주로 컴파일러에게 정보를 제공하거나, 런타임에 특정 동작을 수행하기 위해 사용됩니다. 어노테이션은 코드의 특정 요소(클래스, 메서드, 변수 등)와 연관된 정보를 전달하는 데 사용됩니다.

14.2 어노테이션의 기본 구조

어노테이션은 @ 기호로 시작하며, 특정 메타데이터를 포함합니다.

public class Example {
    @Override
    public String toString() {
        return "Example class";
    }
}

위 예시에서 @Override 어노테이션은 해당 메서드가 슈퍼 클래스의 메서드를 오버라이드하고 있음을 컴파일러에게 알려줍니다.

14.3 자주 사용하는 어노테이션

  • @Override: 메서드가 슈퍼 클래스의 메서드를 오버라이드하고 있음을 나타냅니다.

  • @Deprecated: 더 이상 사용되지 않으며, 앞으로 제거될 예정임을 나타냅니다.

  • @SuppressWarnings: 컴파일러 경고를 무시하도록 지시합니다.

14.4 커스텀 어노테이션

자바에서는 사용자 정의 어노테이션을 만들 수 있습니다. 예를 들어, 특정 메서드가 실행되기 전에 로그를 기록하는 어노테이션을 만들 수 있습니다.

java코드 복사@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecutionTime {
}

15. 어노테이션을 왜 사용할까요?

15.1 코드 가독성 및 유지보수성 향상

어노테이션은 코드에 메타데이터를 추가함으로써, 코드의 가독성과 유지보수성을 향상시킬 수 있습니다. 예를 들어, @Override 어노테이션을 사용하면 오버라이드된 메서드임을 명확히 알 수 있어, 코드의 이해도를 높일 수 있습니다.

15.2 메타데이터 제공

어노테이션은 컴파일러에게 특정 정보를 제공하거나, 런타임에 리플렉션을 통해 메타데이터를 활용할 수 있도록 도와줍니다. 이를 통해 코드를 자동 생성하거나, 특정 동작을 런타임에 동적으로 적용할 수 있습니다.

15.3 프레임워크와의 통합

많은 자바 프레임워크에서 어노테이션을 사용하여 설정을 관리합니다. 예를 들어, 스프링(Spring) 프레임워크에서는 @Autowired 어노테이션을 사용하여 의존성 주입을 설정할 수 있습니다. 이는 XML 설정 파일을 사용하는 것보다 직관적이고, 오류를 줄일 수 있습니다.

16. 어노테이션은 리플렉션으로 동작한다고 말씀해 주셨는데, 리플렉션은 무엇인가요?

16.1 리플렉션의 정의

리플렉션(Reflection)은 자바에서 런타임에 클래스의 메타데이터(클래스 정보, 메서드, 필드 등)를 동적으로 조사하고 조작할 수 있는 기능입니다. 리플렉션을 사용하면 컴파일 타임에는 알 수 없는 객체의 정보를 런타임에 얻을 수 있습니다.

16.2 리플렉션의 주요 기능

  • 클래스 정보 조회: 클래스의 이름, 패키지, 상위 클래스 등을 런타임에 조회할 수 있습니다.

  • 필드와 메서드 접근: 클래스의 필드와 메서드에 접근하고, 값을 조회하거나 수정할 수 있습니다.

  • 동적 객체 생성: 리플렉션을 사용하여 클래스의 인스턴스를 동적으로 생성할 수 있습니다.

16.3 리플렉션의 예시

Class<?> clazz = Class.forName("com.example.MyClass");
Method method = clazz.getMethod("myMethod");
method.invoke(clazz.newInstance());

위 코드에서 리플렉션을 통해 MyClass라는 클래스의 메서드 myMethod를 동적으로 호출하고 있습니다.

16.4 리플렉션의 장점

  • 동적 코드 실행: 컴파일 시점에 알 수 없는 클래스나 메서드를 런타임에 실행할 수 있습니다.

  • 프레임워크 개발: 많은 자바 프레임워크가 리플렉션을 사용하여 애플리케이션의 구조를 동적으로 조작하고, 설정을 자동화합니다.

16.5 리플렉션의 단점

  • 성능: 리플렉션은 일반적인 메서드 호출보다 느릴 수 있습니다.

  • 안전성: 컴파일 타임에 타입 검사가 이루어지지 않기 때문에, 런타임에 발생하는 오류가 증가할 수 있습니다.

  • 보안: 리플렉션을 사용하면 일반적으로 접근할 수 없는 필드나 메서드에 접근할 수 있어, 보안 취약점이 발생할 수 있습니다.

17. 리플렉션을 활용해서 어노테이션의 메타 데이터를 가져오는 등의 로직을 실제로 구현해 보신 적이 있으신가요?

테스트 코드를 작성할때, private으로 지정된 메서드를 테스트하기 위해서 사용할 수 있습니다.

public class Add {
  private int add(int a, int b) {
      return a + b;
  }
}
import org.junit.Test;
import static org.junit.Assert.*;

import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method;

public Test {
	
    @Test
    public void test() {
		Method method = Add.class.getDeclaredMethod("add", int.class, int.class);
        method.setAccessible(true);
        int ret = method.invoke(1, 2);
        assertEquals(3, ret);
    }
}

18. System.out.println 클래스는 성능이 좋지 않다고 하는데 이유가 무엇일까요?

18.1 System.out.println의 작동 방식

System.out.println은 콘솔에 메시지를 출력하는 메서드로, 내부적으로는 I/O 작업을 수행합니다. I/O 작업은 일반적으로 CPU 연산보다 시간이 오래 걸리며, 특히 대량의 데이터를 출력할 때 성능에 부정적인 영향을 미칠 수 있습니다.

18.2 주요 성능 문제

  • 동기화: System.out.println 메서드는 동기화된(synchronized) 메서드입니다. 이는 여러 스레드가 동시에 println을 호출할 때, 스레드 간의 경쟁이 발생하지 않도록 보호하지만, 그로 인해 성능 저하가 발생할 수 있습니다.

  • I/O 비용: 콘솔 출력은 파일 시스템 또는 네트워크를 통해 데이터를 전송하는 것과 같이 느린 I/O 작업을 포함합니다. 이러한 I/O 작업은 시간이 많이 소요되며, 특히 반복적인 출력 작업이 성능 저하의 원인이 될 수 있습니다.

  • 버퍼링 미비: System.out.println은 버퍼링 없이 데이터를 즉시 출력하기 때문에, 출력 성능이 저하될 수 있습니다. 반면, BufferedWriter와 같은 클래스는 버퍼를 사용하여 I/O 작업을 최적화합니다.

18.3 성능 최적화 방안

  • 로그 프레임워크 사용: 성능이 중요한 애플리케이션에서는 System.out.println 대신 Log4j, SLF4J와 같은 로그 프레임워크를 사용하는 것이 좋습니다. 이러한 프레임워크는 비동기 로깅, 파일 로깅, 로그 레벨 설정 등의 기능을 제공하여 성능을 개선할 수 있습니다.

  • 버퍼링 사용: BufferedWriter와 같은 버퍼링 클래스를 사용하여 출력 성능을 최적화할 수 있습니다.

System.out.println은 간단한 디버깅이나 소규모 애플리케이션에서 유용하지만, 대규모 애플리케이션에서는 성능 문제를 야기할 수 있습니다. 이러한 이유로, 성능이 중요한 경우에는 로그 프레임워크나 버퍼링 기술을 사용하는 것이 좋습니다.

PreviousWeek 2(1/2) - String, Exception, GenericNextWeek3(1/2) Collections

Last updated 8 months ago