用于序列化单例的瞬态 [英] transient for serializing singleton

查看:121
本文介绍了用于序列化单例的瞬态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有效Java - 为了保持单例保证,你需要
声明所有实例字段瞬态并提供'readResolve'方法。
我们通过在这里声明字段瞬态来实现什么?
以下是样本:

Effective Java - To maintain the singleton guarantee, you have to declare all instance fields transient and provide a 'readResolve' method. What do we achieve by declaring the fields transient here? Here's a sample:

....
....
public final class MySingleton implements Serializable{
 private int state;
 private MySingleton() { state =15; }
 private static final MySingleton INSTANCE = new MySingleton();
 public static MySingleton getInstance() { return INSTANCE; }
 public int getState(){return state;}
public void setState(int val){state=val;}
private Object readResolve() throws ObjectStreamException {
  return INSTANCE; 
 }
    public static void main(String[] args) {
        MySingleton  c = null;
        try {
            c=MySingleton.getInstance();
            c.setState(25);
            FileOutputStream fs = new FileOutputStream("testSer.ser");
            ObjectOutputStream os = new ObjectOutputStream(fs);
            os.writeObject(c);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            FileInputStream fis = new FileInputStream("testSer.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            c = (MySingleton) ois.readObject();
            ois.close();
            System.out.println("after deser: contained data is " + c.getState());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

无论是谁我是否将'state'变量声明为瞬态变量,我将c.getState()gettign打印为25.
我在这里遗漏了什么?

Irrespective of whether I declare the 'state' variable as transient or not ,I get c.getState() gettign printed out as 25. Am I Missing something here?

推荐答案

通过使属性瞬态获得的是您不会序列化状态。序列化它是不必要的,因为它无论如何都被readResolve()方法丢弃。

What you gain by making the attribute transient is that you don't serialize the state. Serializing it is unnecessary, since it's discarded anyway by the readResolve() method.

如果状态包含int,则无关紧要。但如果状态是对象的复杂图形,则会产生显着的性能差异。当然,如果状态不是可序列化的,那么你没有任何其他选择。

If the state consists in an int, it doesn't matter much. But if the state is a complex graph of objects, it makes a significant performance difference. And of course, if the state is not serializable, you don't have any other choice.

这就是说,序列化单例是值得怀疑的。

That said, serializing a singleton is questionable.

这篇关于用于序列化单例的瞬态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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