gpt4 book ai didi

java - 如何正确且线程安全地重用Jackson ObjectReader?

转载 作者:行者123 更新时间:2023-12-02 04:43:10 29 4
gpt4 key购买 nike

Jackson 有 ObjectReader,文档说您需要使用它来保证线程安全。但我不明白如何正确地做到这一点

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;

import java.io.IOException;
import java.util.Map;

public class JsonParser {
private ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private ObjectReader OBJECT_READER = new ObjectMapper().readerFor(Map.class);

public Map<String, String> parseJson1(String json) throws IOException {
ObjectReader objectReader = OBJECT_MAPPER.readerFor(Map.class);
return objectReader.readValue(json);
}

public Map<String, String> parseJson2(String json) throws IOException {
return OBJECT_READER.readValue(json);
}
}

我写了两个示例

  1. parseJson1() - 在每次解析时从 ObjectMapper 创建 ObjectReader
  2. parseJson2() - 在 ObjectReader 上重用单个实例

哪一个是正确的?

最佳答案

文档说它是“完全线程安全的”,这意味着您可以安全地使用 parseJson2 而不必担心在并发线程中调用此方法。

https://fasterxml.github.io/jackson-databind/javadoc/2.5/com/fasterxml/jackson/databind/ObjectReader.html

Uses "fluent" (or, kind of, builder) 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.

关于java - 如何正确且线程安全地重用Jackson ObjectReader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335646/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com