我做了下面的示例代码来检查 JsonPath 版本 2.9.0 线程安全与否,我意识到它不安全。 这是 JsonPath 的问题还是有什么办法解决它?或者有什么替代解决方案?请帮忙
@Test
public void testJsonPath() throws IOException {
String jsonString = "{\"test\":1,\"person\":{\"name\":\"John\",\"age\":50}}";
String jsonString2 ="{\"test\":1,\"person\":{\"name\":\"Babara\",\"age\":48}}";
Thread thread1 = new Thread(createRunnable(jsonString));
Thread thread2 = new Thread(createRunnable(jsonString2));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private Runnable createRunnable(String json) {
return () -> {
int count = 10;
try {
while (count > 0) {
count--;
Thread.sleep(1000);
String value = JsonPath.read(json, "concat($.person.name, $.person.age)");
if (value.equals("John48") || value.equals("Babara50")) {
System.out.println("Wrong value returned: " + value);
}
System.out.printf("Thread-[%d], Value: [%s]%n", Thread.currentThread().getId(), value);
}
} catch (Exception e) {
e.printStackTrace();
}
};
}
结果显示JsonPath返回错误值,如:Babara50,John48
Thread-[30], Value: [John50]
Thread-[31], Value: [Babara48]
Thread-[30], Value: [John50]
Thread-[31], Value: [Babara48]
Thread-[31], Value: [Babara48]
Thread-[30], Value: [John50]
Thread-[31], Value: [Babara48]
Thread-[30], Value: [**Babara50**]
Thread-[31], Value: [**John48**]
Thread-[30], Value: [John50]
Thread-[31], Value: [Babara48]
Thread-[30], Value: [**Babara50**]
Thread-[30], Value: [John50]
Thread-[31], Value: [**John48**]
Thread-[31], Value: [**John48**]
Thread-[30], Value: [John50]
Thread-[31], Value: [Babara48]
Thread-[30], Value: [John50]
Thread-[31], Value: [Babara48]
Thread-[30], Value: [John50]
jayway
JsonPath 实现使用在调用JsonPath.read
时维护的缓存。
您可以通过设置一个永远找不到任何东西的虚拟缓存来禁用缓存:
CacheProvider.setCache(new Cache() {
@Override
public JsonPath get(String key) {
return null;
}
@Override
public void put(String key, JsonPath value) {
}
});