Skip to content

Commit

Permalink
[AVRO-4042] Precache ObjectMapper to avoid recreation (#3123)
Browse files Browse the repository at this point in the history
ObjectMapper is an expensive, immutable and thread-safe object.
By creating just one instance, we can avoid unnecessary recalculations.
  • Loading branch information
andrew-ie authored Aug 29, 2024
1 parent c7b79bf commit 971b0a8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@
*/
public class SchemaBuilder {

private static final ObjectMapper MAPPER = new ObjectMapper();

private SchemaBuilder() {
}

Expand Down Expand Up @@ -2734,7 +2736,7 @@ private static JsonNode toJsonNode(Object o) {
} else {
s = GenericData.get().toString(o);
}
return new ObjectMapper().readTree(s);
return MAPPER.readTree(s);
} catch (IOException e) {
throw new SchemaBuilderException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@
import com.fasterxml.jackson.databind.util.TokenBuffer;

public class JacksonUtils {
/**
* Object Mapper used for toJsonNode method.
*/
private static final ObjectMapper MAPPER = new ObjectMapper();

/**
* This object mapper uses a special variant that has different visibility
* rules, used in objectToMap method.
*/
private static final ObjectMapper OBJECT_TO_MAP_MAPPER = MAPPER.copy()
.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

private JacksonUtils() {
}
Expand All @@ -50,9 +62,9 @@ public static JsonNode toJsonNode(Object datum) {
return null;
}
try {
TokenBuffer generator = new TokenBuffer(new ObjectMapper(), false);
TokenBuffer generator = new TokenBuffer(MAPPER, false);
toJson(datum, generator);
return new ObjectMapper().readTree(generator.asParser());
return MAPPER.readTree(generator.asParser());
} catch (IOException e) {
throw new AvroRuntimeException(e);
}
Expand Down Expand Up @@ -194,10 +206,6 @@ public static Object toObject(JsonNode jsonNode, Schema schema) {
* @return Its Map representation
*/
public static Map objectToMap(Object datum) {
ObjectMapper mapper = new ObjectMapper();
// we only care about fields
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
return mapper.convertValue(datum, Map.class);
return OBJECT_TO_MAP_MAPPER.convertValue(datum, Map.class);
}
}

0 comments on commit 971b0a8

Please sign in to comment.