简体   繁体   English

如何在这里最大程度地提高JSONParser的效率?

[英]How to maximise efficiency of JSONParser here?

I'm an amazing noob when it comes to threading, honestly. 老实说,我是一个很棒的菜鸟。 This is literally scampered together from the documentation, it's probably not even correct or necessary. 从字面上看,这是从文档中彻底删除的,甚至可能是不正确或不必要的。

I'm working with a class I've created for fetching data from Mojang's API, the methods are static and I'm unsure how to tackle the usage of a JSONParser (json-simple library) object. 我正在使用为从Mojang的API提取数据而创建的类,该方法是静态的,并且我不确定如何处理JSONParser(json-简单库)对象的用法。

My original code is on this gist and the code I'm experimenting with is here . 我的原始代码在这个要点上 ,而我正在尝试的代码在这里 In the second gist I've made the JSONParser static, noting that it wasn't thread-safe I used a synchronized getter to access it where needed, whereas in my first gist I'm creating a new JSONParser object for each method call. 在第二个要点中,我将JSONParser设为静态,并指出它不是线程安全的,因此我在需要的地方使用了synchronized getter访问它,而在第一个要点中,我为每个方法调用创建了一个新的JSONParser对象。

Given that the code will often be run on another thread is the way I access the static JSONParser efficient or would I just be best sticking to the code in the first gist? 鉴于代码通常会在另一个线程上运行,这是我高效访问静态JSONParser的方式,还是我最好还是坚持第一个要点上的代码?

According to the documentation of JSONParser , the class is not thread safe. 根据JSONParser的文档 ,该类不是线程安全的。 So you either need proper locking or create one parser per thread. 因此,您要么需要适当的锁定,要么为每个线程创建一个解析器。

A better design is probably to make all the public methods non-static and the JSONparser non-static as well. 更好的设计可能是使所有公共方法都是非静态的,并且使JSONparser为非静态的。 That way, you can create one Fetcher per thread. 这样,您可以为每个线程创建一个Fetcher

OTOH, creating JSONparser is pretty cheap so unless you need millions of them per second, just create a new one per request. OTOH,创建JSONparser相当便宜,因此除非您每秒需要数百万个,否则只需为每个请求创建一个新的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM