Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#1935] Improvement(common): improve ObjectMapper with lazy singleton approach (#2169)

YongXingf58917761731
diff --git a/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java b/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java
index 7075916c91..9489438bdb 100644
--- a/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java
+++ b/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java
@@ -212,7 +212,22 @@ public class JsonUtils {
}
}
- private static volatile ObjectMapper mapper = null;
+ /**
+ * ObjectMapperHolder is a static inner class that holds the instance of ObjectMapper. This class
+ * utilizes the Initialization-on-demand holder idiom, which is a lazy-loaded singleton. This
+ * idiom takes advantage of the fact that inner classes are not loaded until they are referenced.
+ * It's a thread-safe and efficient way to implement a singleton as the instance is created when
+ * it's needed at the first time.
+ */
+ private static class ObjectMapperHolder {
+ private static final ObjectMapper INSTANCE =
+ JsonMapper.builder()
+ .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
+ .configure(EnumFeature.WRITE_ENUMS_TO_LOWERCASE, true)
+ .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS)
+ .build()
+ .registerModule(new JavaTimeModule());
+ }
/**
* Get the shared ObjectMapper instance for JSON serialization/deserialization.
@@ -220,21 +235,7 @@ public class JsonUtils {
* @return The ObjectMapper instance.
*/
public static ObjectMapper objectMapper() {
- if (mapper == null) {
- synchronized (JsonUtils.class) {
- if (mapper == null) {
- mapper =
- JsonMapper.builder()
- .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
- .configure(EnumFeature.WRITE_ENUMS_TO_LOWERCASE, true)
- .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS)
- .build()
- .registerModule(new JavaTimeModule());
- }
- }
- }
-
- return mapper;
+ return ObjectMapperHolder.INSTANCE;
}
/**