可以将 Gson 实例用作模型 bean 中的静态字段(重用)吗? [英] Is it OK to use Gson instance as a static field in a model bean (reuse)?

查看:24
本文介绍了可以将 Gson 实例用作模型 bean 中的静态字段(重用)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我实现的模型:

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);
    }
}

我认为为每个 LoginSession 实例创建新的 Gson 实例是没有用的.

I thought it's useless to create new Gson instance for every LoginSession instance.

但我担心的是线程安全问题.大约每秒将创建 1000 多个实例.

But what I'm worried about is thread-safety issues. Approximately 1000+ instances/sec will be created.

使用 Gson 实例作为静态字段可以吗?

Is it OK to use Gson instance as static field?

感谢您的任何建议/更正.

Thanks for any advices/corrections.

推荐答案

对我来说似乎很好.GSON 实例中没有任何内容使其与 LoginSession 的特定实例相关,因此它应该是静态的.

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 实例应该是线程安全的,并且有一个错误已修复.

GSON instances should be thread-safe, and there was a bug regarding that which was fixed.

这篇关于可以将 Gson 实例用作模型 bean 中的静态字段(重用)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆