Java 21 Features with Spring
π‘ Spring Boot 3.2 + Java 21 μ°κ³ νμ© μμ
1. β Virtual Threads + Spring Boot 3.2
Java 21μ κ°μ μ€λ λ(Virtual Thread) μ Spring Boot 3.2λ κΈ°λ³Έμ μΌλ‘ νΈνλ©λλ€.
π μ£Όμ ν¨κ³Ό
- κΈ°μ‘΄
@RestController
κΈ°λ° μλΈλ¦Ώ API (Tomcat) λ κ°μ μ€λ λλ‘ μ€ν κ°λ₯ - λΉλκΈ° νλ‘κ·Έλλ° μμ΄λ κ³ μ±λ₯ μ²λ¦¬ κ°λ₯ β λκΈ°μ μ½λλ‘λ λμ λμμ±
βοΈ μ€μ λ°©λ²
1
2
3
4
# application.yml
server:
tomcat:
protocol: org.apache.coyote.http11.Http11Nio2Protocol
1
2
3
4
@Bean
public TomcatProtocolHandlerCustomizer<?> protocolHandlerVirtualThreadExecutor() {
return protocolHandler -> protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
}
π κΈ°λ ν¨κ³Ό
- κΈ°μ‘΄μ
WebClient
,CompletableFuture
,@Async
μμ΄λ λμμ± ν₯μ - μμ² μκ° λ§μ API μλ²μ μ ν© (μ: λμ©λ λ°°μΉ μ²λ¦¬, IO-bound μλΉμ€)
2. β Scoped Values
ThreadLocal
λ체: κ°μ μ€λ λμμλ μμ νκ² μ¬μ© κ°λ₯
1
2
3
4
5
6
7
ScopedValue<String> USER_ID = ScopedValue.newInstance();
public void controller() {
ScopedValue.where(USER_ID, "user-123").run(() -> {
service(); // λ΄λΆμ μΌλ‘ USER_ID.get() μ¬μ© κ°λ₯
});
}
- β νΈλμμ ID, μμ²μ ID, νμμ‘΄ λ± μ»¨ν μ€νΈ μ νμ μ ν©
- π« κΈ°μ‘΄
ThreadLocal
μ κ°μ μ€λ λμ κΆν©μ΄ μ μ’μ β μ΄κ±Έλ‘ λ체 κ°λ₯
3. β
Pattern Matching for switch
/ Record Patterns
μμ² DTO, 컀맨λ νΈλ€λ¬ λ±μμ ν¨ν΄ κΈ°λ° λΆκΈ° μ²λ¦¬
1
2
3
4
5
6
7
8
9
10
sealed interface Command permits CreateUser, DeleteUser {}
record CreateUser(String name) implements Command {}
record DeleteUser(Long id) implements Command {}
public void handle(Command command) {
switch (command) {
case CreateUser(var name) -> userService.create(name);
case DeleteUser(var id) -> userService.delete(id);
}
}
- π‘ 볡μ‘ν
if-else
/instanceof
λΆκΈ°λ¬Έ μ κ±° - μλΉμ€ κ³μΈ΅μ λΆκΈ° λ‘μ§μ λͺ ννκ³ νμ μμ νκ² κ΅¬ν κ°λ₯
4. β Foreign Function & Memory API
μμ§ Springμμλ μ§μ νμ© μ¬λ‘κ° μ μ§λ§, κ³ μ±λ₯ λ€μ΄ν°λΈ νΈμΆ μ μ¬μ© κ°λ₯
μ: C κΈ°λ° μμ λΆμ λΌμ΄λΈλ¬λ¦¬, μμ μΈμ½λ© λ±κ³Όμ μ°λμ νμ©
5. β Sequenced Collections
컨νΈλ‘€λ¬λ μλΉμ€μμ μμκ° μ€μν λ°μ΄ν° λ€λ£° λ λͺ μμ μΈν°νμ΄μ€ μ¬μ© κ°λ₯
1
2
3
SequencedSet<String> history = new LinkedHashSet<>();
history.addFirst("eventA");
history.addLast("eventB");
LinkedHashSet
,LinkedHashMap
λ±μ λ λͺ ννκ² νμ© κ°λ₯- ν νλ¦Ώ μμ§, νμ€ν 리 λ‘κ·Έ, μμ°¨ UI λ λλ§μμ μ μ©
β μ 리: μ€λ¬΄ μ μ© κ°μ΄λ
κΈ°λ₯ | Spring μ€λ¬΄ νμ© |
---|---|
Virtual Threads | Tomcat κ°μ μ€λ λ μ€μ β IO μ±λ₯ ν₯μ |
Scoped Values | μμ² μ»¨ν μ€νΈ μ ν (ex. userId, traceId) |
Record Patterns | Command/DTO μ²λ¦¬ λ‘μ§ κ°κ²°ν |
Sequenced Collections | μμ μλ λ°μ΄ν° μ²λ¦¬ λͺ ννκ² |
Foreign Function API | JNI λ체 (λ€μ΄ν°λΈ λΌμ΄λΈλ¬λ¦¬ νΈμΆ) |
This post is licensed under CC BY 4.0 by the author.