我做了下面的示例代码来判断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]

推荐答案

这是由这个bug https://github.com/json-path/JsonPath/issues/975引起的,正如Vova Bilychat在 comments 中指出的那样.

jayway JsonPath实现使用了一个缓存,该缓存在调用JsonPath.read时维护.

您可以通过设置一个永远不会找到任何东西的虚拟缓存来禁用缓存:

CacheProvider.setCache(new NOOPCache());

Java相关问答推荐

使用log 4j2格式的Hibernate 显示SQL日志(log)

ittext pdf延迟签名,签名无效

Java List with all combinations of 8 booleans

给定Java枚举类,通过值查找枚举

JVM会优化这个数学运算吗?

Java FX中的河内之塔游戏-在游戏完全解决之前什么都不会显示

使用意向过滤器从另一个应用程序启动服务

使用REST客户端和对象映射器从字符串反序列化Json

如何使用Jackson将XML元素与值和属性一起封装

如何集成语义发布和BitBucket(Java项目)

如何仅使用键/ID的一部分(组合)高效地返回映射值?

Cordova Android Gradle内部版本组件不兼容

如何在EL处理器中定义带有命名空间的变量?

协同 routine 似乎并不比JVM线程占用更少的资源

如何在Maven Central上部署?

JXBrowser是否支持加载Chrome扩展?

如何使用Java ZoneID的区域设置?

Java System.getProperty在哪里检索user.home?

PhantomReference无法访问时会发生什么?

放置在变量中的Java成员引用不相等