java 如何正确和线程安全地重用 Jackson ObjectReader?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35335646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How correctly and thread safe reuse Hymanson ObjectReader?
提问by Nawa
Hymanson have ObjectReader and documentation says that you need to use it for thread safety. But I can't understand how to do it correctly
Hymanson 有 ObjectReader 并且文档说你需要使用它来保证线程安全。但我不明白如何正确地做到这一点
import com.fasterxml.Hymanson.databind.ObjectMapper;
import com.fasterxml.Hymanson.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);
}
}
I wrote two samples
我写了两个样本
parseJson1()
- creates ObjectReader from ObjectMapper on each parsingparseJson2()
- reuses single instance on ObjectReader
parseJson1()
- 在每次解析时从 ObjectMapper 创建 ObjectReaderparseJson2()
- 在 ObjectReader 上重用单个实例
Which of them is right?
他们哪个是对的?
回答by vvg
Documentation said it's "fully thread-safe" it means you can use parseJson2
safely without worring about invoking this method in concurrent threads.
文档说它是“完全线程安全的”,这意味着您可以parseJson2
安全地使用,而不必担心在并发线程中调用此方法。
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.
使用“流畅”(或某种构建器)模式,因此实例是不可变的(因此完全线程安全,没有外部同步);新实例是为不同的配置构建的。实例最初由 ObjectMapper 构造,可以复用、共享、缓存;一方面是因为线程安全,另一方面是因为实例相对较轻。