将Gson实例用作模型bean中的静态字段(重用)可以吗? [英] Is it OK to use Gson instance as a static field in a model bean (reuse)?
问题描述
public class LoginSession {
private static final Gson gson = new Gson( );
私人字符串ID;
私人字符串名称;
私人长时间戳;
public LoginSession(String id,String name){
this.id = id;
this.name = name;
this.timestamp = System.currentTimeMillis();
}
public String toJson(){
return gson.toJson(this);
public static LoginSession fromJson(String json){
checkArgument(!isNullOrEmpty(json));
返回gson.fromJson(json,LoginSession.class);
}
}
我认为每次创建新的Gson实例都是没用的LoginSession实例。
但我担心的是线程安全问题。将创建约1000+个实例/秒。
可以使用Gson实例作为静态字段吗?
感谢您的任何建议/更正。 p>
对我来说这似乎很好。 GSON实例中没有任何内容与 LoginSession
的特定实例相关,所以它应该是静态的。
Here's the model I implemented:
public class LoginSession {
private static final Gson gson = new Gson();
private String id;
private String name;
private long timestamp;
public LoginSession(String id, String name) {
this.id = id;
this.name = name;
this.timestamp = System.currentTimeMillis();
}
public String toJson() {
return gson.toJson(this);
}
public static LoginSession fromJson(String json) {
checkArgument(!isNullOrEmpty(json));
return gson.fromJson(json, LoginSession.class);
}
}
I thought it's useless to create new Gson instance for every LoginSession instance.
But what I'm worried about is thread-safety issues. Approximately 1000+ instances/sec will be created.
Is it OK to use Gson instance as static field?
Thanks for any advices/corrections.
It seems just fine to me. There is nothing in the GSON instance that makes it related to a specific instance of LoginSession
, so it should be static.
GSON instances should be thread-safe, and there was a bug regarding that which was fixed.
这篇关于将Gson实例用作模型bean中的静态字段(重用)可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!