JDK21 Update 정리

2023. 11. 22. 13:47· 언어/java
목차
  1. 서론
  2. 주요 업데이트 내용
  3. Record Patterns
  4. Pattern Matching for switch
  5. Virture Thread 표준화
  6. Virture Thread 사용 예시
  7. Structured Thread 사용 예시
  8. Sequenced Collection
  9. Unnamed Classes and Instance Main Methods
  10. Unnamed Patterns and Variables
반응형

서론

JDK 21이 발표됨에 따라 관련 업데이트 내용 정리
JDK 17 이후 최신 LTS 버전

주요 업데이트 내용

  • Record Patterns
  • Pattern Matching for switch
  • Virture Thread 표준화
  • Sequenced Collection
  • Unnamed Classes and Instance Main Methods
  • Unnamed Patterns and Variables

Record Patterns

  • Record 타입에 대한 destructed가 가능해졌다.

패턴 매칭

// As of Java 16
record Point(int x, int y) {}

static void printSum(Object obj) {
    if (obj instanceof Point p) {
        int x = p.x();
        int y = p.y();
        System.out.println(x+y);
    }
}

// As of Java 21
static void printSum(Object obj) {
    if (obj instanceof Point(int x, int y)) {
        System.out.println(x+y);
    }
}

중첩 패턴

// As of Java 16
record Point(int x, int y) {}
enum Color { RED, GREEN, BLUE }
record ColoredPoint(Point p, Color c) {}
record Rectangle(ColoredPoint upperLeft, ColoredPoint lowerRight) {}

// As of Java 21
static void printColorOfUpperLeftPoint(Rectangle r) {
    if (r instanceof Rectangle(ColoredPoint(Point p, Color c),
                               ColoredPoint lr)) {
        System.out.println(c);
    }
}

Pattern Matching for switch

  • switch문에서 instanceOf로 체크한 Object에 대해 자동으로 형변환이 되도록 개선되었다.
// JDK 16 이전
if (obj instanceof String) {
    String s = (String)obj;
    ... use s ...
}

// JDK 16
if (obj instanceof String s) {
    ... use s ...
}

// JDK 21 이전
static String formatter(Object obj) {
    String formatted = "unknown";
    if (obj instanceof Integer i) {
        formatted = String.format("int %d", i);
    } else if (obj instanceof Long l) {
        formatted = String.format("long %d", l);
    } else if (obj instanceof Double d) {
        formatted = String.format("double %f", d);
    } else if (obj instanceof String s) {
        formatted = String.format("String %s", s);
    }
    return formatted;
}

// JDK 21
static String formatterPatternSwitch(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        default        -> obj.toString();
    };
}

Virture Thread 표준화

  • JDK 19에서 등장했던 Virture Thread의 표준화
  • JDK 20에서 Structured Concurrency 제공으로, Thread에서 동시성 관련 이슈에 제어

Virture Thread 사용 예시

@SpringBootTest
public class VirtureThreadTest {
    private static final Logger log = Logger.getAnonymousLogger();

    @Test
    public void 가상_스레드를_확인한다() throws InterruptedException{
        log.info("\nthreadName: " + Thread.currentThread().getName() + "\navailableProcessors: " + Runtime.getRuntime().availableProcessors());

        final long start = System.currentTimeMillis();
        final AtomicLong index = new AtomicLong();
        final int count = 100;
        final CountDownLatch countDownLatch = new CountDownLatch(count);

        final Runnable runnable = () -> {
            try {
                final long indexValue = index.incrementAndGet();
                Thread.sleep(1000L);

                log.info("\nthreadName: " + Thread.currentThread().getName() + "\nvalue: " + indexValue);
                countDownLatch.countDown();
            } catch (final InterruptedException e) {
                countDownLatch.countDown();
            }
        };

        try (final ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < count; i++) {
                executorService.submit(runnable);
            }
        }

        countDownLatch.await();
        final long finish = System.currentTimeMillis();
        final long timeElapsed = finish - start;

        log.info("\nthreadName: " + Thread.currentThread().getName() + "\nRun time: " + timeElapsed);
    }
}

Structured Thread 사용 예시

@SpringBootTest
public class StructuredThreadTest {
    @Test
    public void 중간_작업이_실패하면_모든_작업이_종료된다() {
        Assertions.assertThrows(RuntimeException.class, () -> {
            try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
                Supplier<List<String>> list = scope.fork(this::list);
                Supplier<String> str = scope.fork(this::str);
                list.get().forEach(System.out::println); // 찍히지 않는다.

                scope.join().throwIfFailed();

                assertEquals("This is String", str.get());

            } catch(InterruptedException | ExecutionException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });
    }

    public String str() {
        throw new RuntimeException();
    }

    public List<String> list() {
        List<String> result = new ArrayList<>() ;

        IntStream
                .range(0, 100)
                .forEach(index -> result.add("This is list_" + index));

        return result;
    }
}

Sequenced Collection

  • 기존에 Collection의 마지막 요소에 접근하려면 list.get(list.size()-1);로 접근해야 했던 불편함이 개선되었다.
@SpringBootTest
public class SequencedCollectionsTest {
    @Test
    public void 마지막_요소를_가져온다() {
        List<Integer> result = new ArrayList<>() ;

        IntStream
                .range(0, 100)
                .forEach(result::add);

        Assertions.assertEquals(99, result.getLast());
    }

    @Test
    public void 현재_마지막_요소를_제거한후_마지막_요소를_가져온다() {
        List<Integer> result = new ArrayList<>() ;

        IntStream
                .range(0, 100)
                .forEach(result::add);

        result.remove(99);

        Assertions.assertEquals(98, result.getLast());
    }
}

Unnamed Classes and Instance Main Methods

  • java method 실행 시에 사용자 편의성을 위한 고안으로 다음과 같이 작성
// JDK 21 이전
public class HelloWorld { 
    public static void main(String[] args) { 
        System.out.println("Hello, World!");
    }
}

// JDK 21
class HelloWorld { 
    void main() { 
        System.out.println("Hello, World!");
    }
}

Unnamed Patterns and Variables

  • 메서드 내 객체 파라미터를 참조하지 않을 경우 '_'로 선언
    for (Object _ : list) {
      ...
      anyMethod();
      ...
    }
반응형
LIST

'언어 > java' 카테고리의 다른 글

[시스템 프로그래밍] JVM 실행 흐름에 대한 코드 분석  (0) 2024.07.17
JDK 동적 프록시  (2) 2023.12.05
[Java] 자바의 컬렉션(Collection)  (1) 2020.05.10
JAVA EE,SE,ME에 대하여  (0) 2019.08.08
JDK와 JRE  (0) 2019.08.08
  1. 서론
  2. 주요 업데이트 내용
  3. Record Patterns
  4. Pattern Matching for switch
  5. Virture Thread 표준화
  6. Virture Thread 사용 예시
  7. Structured Thread 사용 예시
  8. Sequenced Collection
  9. Unnamed Classes and Instance Main Methods
  10. Unnamed Patterns and Variables
'언어/java' 카테고리의 다른 글
  • [시스템 프로그래밍] JVM 실행 흐름에 대한 코드 분석
  • JDK 동적 프록시
  • [Java] 자바의 컬렉션(Collection)
  • JAVA EE,SE,ME에 대하여
iron_jin
iron_jin
배운 것에 대한 내 생각을 가지고 정리하자
學而不思則罔(학이불사즉망)배운 것에 대한 내 생각을 가지고 정리하자
iron_jin
學而不思則罔(학이불사즉망)
iron_jin
전체
오늘
어제
  • 전체 (163)
    • 도서 (10)
    • 생각 정리 (0)
    • 후기 모음 (14)
    • 언어 (20)
      • css (1)
      • java (9)
      • Kotlin (0)
      • javascript (0)
      • Solidity (3)
      • Python (3)
      • GO (3)
      • C++ (1)
    • Spring Framework (32)
      • spring (16)
      • JPA (6)
      • Error (4)
      • Settings (4)
    • 알고리즘 (62)
      • 이론 (0)
      • 연습문제 (58)
    • 인프라 (6)
      • 클라우드 (1)
      • 도커 (0)
      • AWS (4)
      • Elastic Search (0)
    • 쿠버네티스 (3)
      • 이론 (0)
      • 실습 (2)
      • 트러블슈팅 (1)
    • Nginx (2)
    • CS (4)
      • 서버 (0)
      • 리눅스 (2)
      • 네트워크 (0)
      • OAuth (2)
    • 형상관리 (3)
      • GIT (3)
    • Open API (3)
      • 카카오 API (1)
      • QGIS (2)
    • 보안 (0)
      • 알고리즘 (0)
    • 공통 (1)
      • 성능 관리 도구 (1)
    • Database (2)
      • MySQL (1)
      • Redis (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Java
  • 2019 카카오 블라인드
  • 항해플러스
  • MySQL
  • 프로그래머스
  • 스프링
  • 2019 카카오
  • 2020 카카오 블라인드
  • Hibernate
  • Python
  • 에릭 에반스
  • 항해99
  • 2020 카카오
  • SpringBoot
  • 알고리즘
  • 코딩테스트
  • 2019 kakao
  • 도메인 주도 개발
  • spring
  • 카카오 겨울 인턴십
  • 자바
  • JPA
  • 2020 kakao
  • ddd
  • 스프링 부트
  • spring boot
  • AWS
  • 백준
  • 2018 카카오 블라인드
  • 2018 kakao

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
iron_jin
JDK21 Update 정리
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.