서론
프로젝트에서 JSON 데이터의 직렬화 및 역직렬화 작업을 위해 Jackson의 ObjectMapper를 사용하고 있다. 효율적인 데이터 처리와 성능 최적화를 위해 객체 재사용이 중요하다. 이에 따라 ObjectMapper를 싱글톤 빈으로 사용하는 것이 적절한지에 대한 고민이 필요하다.
📌 ObjectMapper는 Thread-safe 할까?
✔️ 결론 : 완전히 thread-safe하다고 말할 수 없다.
Jackson의 ObjectMapper는 스레드 간에 공유되어도 안전하게 설계된 부분이 있지만, 완전히 스레드 안전하다고는 할 수 없다. ObjectMapper 인스턴스를 만드는 데 비용이 크기 때문에 인스턴스를 생성하고 재사용하는 게 권장된다.
ObjectMapper itself is only thread-safe when configuring methods (such as this one) are NOT called.
공식 문서에 따르면, 기본적인 직렬화와 역직렬화 작업은 안전하지만 설정을 변경하는 작업은 스레드 안전하지 않다.
Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls. If configuration of a mapper instance is modified after first usage, changes may or may not take effect, and configuration calls themselves may fail.
따라서 ObjectMapper를 멀티스레드 환경에서 사용할 때는 모든 설정을 완료한 후에 사용해야 한다.
설정 관련 작업만 제외하면 멀티스레드 환경에서 비교적 안전하게 사용할 수 있지만, 싱글톤 빈으로 사용할 때는 이러한 조건을 충족해야 한다.
그렇다면 설정 관련만 아니면 멀티 스레드 환경에서 문제가 없을테니 싱글톤 빈으로 사용해도 되는걸까?
📌 ObjectMapper 멀티스레드에서 성능 이슈
ObjectMapper 내부에서 synchronized 블록으로 인한 멀티 스레드 성능 이슈가 존재했다.
https://medium.com/feedzaitech/when-jackson-becomes-a-parallelism-bottleneck-f1440a50b429
When Jackson becomes a parallelism bottleneck
So you know Jackson and you want to understand how it may be hampering the performance of your multi-threaded application?
medium.com
2.8.7 버전부터는 해당 문제가 개선이 되었다고 한다.
📌 ObjectReader, ObjectWriter
✔️ObjectReader
Uses "mutant factory" pattern so that instances are immutable (and thus fully thread-safe with no external synchronization); new instances are constructed for different configurations. Instances are initially constructed by ObjectMapper and can be reused, shared, cached; both because of thread-safety and because instances are relatively light-weight.
✔️ ObjectWriter
Builder object that can be used for per-serialization configuration of serialization parameters, such as JSON View and root type to use. (and thus fully thread-safe with no external synchronization); new instances are constructed for different configurations. Instances are initially constructed by ObjectMapper and can be reused in completely thread-safe manner with no explicit synchronization
ObjectMapper에서 생성할 수 있는 객체로 thread-safe한 불변 객체이다.
멀티스레드 환경에서 설정을 변경해서 써야하는 상황이 온다면 ObjectReader, ObjectWriter 사용도 좋은 선택이다.
'Programming > Java,Back-end' 카테고리의 다른 글
[Java] 익명 클래스와 람다(Lambda) 정리 (0) | 2024.10.29 |
---|---|
[Gradle] runtimeOnly, implementation, compileOnly, api 차이 (0) | 2024.10.26 |
[Java] 메인 메소드 존재 이유, 매개변수 String[] args에 대하여 (0) | 2024.10.26 |
BCrypt matches 동작 방식 : 매번 다른 해싱에도 일치 검증 가능한 이유 (0) | 2024.10.25 |
DAO와 Repository는 다른 개념일까?(차이를 구분할때의 장점) (2) | 2024.05.01 |