采访问题:关于Java序列化和单例 [英] Interview question: about Java serialization and singletons

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

问题描述

在采访中,采访者问我以下问题:是否可以序列化单个对象?我说是的,但在哪种情况下我们应该序列化一个单例?

In an interview the interviewer asked me the following question: is it possible to serialize a singleton object? I said yes, but in which scenario should we serialize a singleton?

是否有可能设计一个对象无法序列化的类?

And is it possible to design a class whose object can not be serialized?

推荐答案

问题应该更好地表达为是否可以使用单例模式类 C 进行序列化和反序列化以一种不破坏单身模式的方式?

The question should probably be better phrased as "is it possible to use serialization and deserialization with a singleton-pattern class C in a way that does not break the singleton pattern?"

答案基本上是肯定的:

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

public class AppState implements Serializable
{
    private static AppState s_instance = null;

    public static synchronized AppState getInstance() {
        if (s_instance == null) {
            s_instance = new AppState();
        }
        return s_instance;
    }

    private AppState() {
        // initialize
    }

    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        ois.defaultReadObject();
        synchronized (AppState.class) {
            if (s_instance == null) {
                // re-initialize if needed

                s_instance = this; // only if everything succeeds
            }
        }
    }

    // this function must not be called other than by the deserialization runtime
    private Object readResolve() throws ObjectStreamException {
        assert(s_instance != null);
        return s_instance;
    }

    public static void main(String[] args) throws Throwable {
        assert(getInstance() == getInstance());

            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos);
            oos.writeObject(getInstance());
            oos.close();

            java.io.InputStream is = new java.io.ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(is);
            AppState s = (AppState)ois.readObject();
            assert(s == getInstance());
    }
}

但请注意使用此代码可以存在 AppState 的多个实例。但是,只引用了一个。其他人有资格进行垃圾收集,仅由反序列化运行时创建,因此它们不存在用于实际目的。

but note that it is possible for multiple instances of AppState to exist using this code. However, only one is referenced. The others are eligible for garbage collection, created only by the deserialization runtime, so they don't exist for practical purposes.

对于其他两个问题的答案(其中)我们应该序列化单例吗?是否可以设计一个对象无法序列化的类?),参见 @ Michael Borgwardt的回答

For answers to your other two questions (In which scenario should we serialize a singleton? Is it possible to design a class whose object can not be serialized?), see @Michael Borgwardt's answer.

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

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