gpt4 book ai didi

java - 面试题: about Java serialization and singletons

转载 作者:IT老高 更新时间:2023-10-28 21:17:34 26 4
gpt4 key购买 nike

在一次采访中,面试官问我以下问题:是否可以序列化单例对象?我说可以,但是在什么场景下我们应该序列化一个单例呢?

是否可以设计一个对象不能序列化的类?

最佳答案

这个问题应该更好地表述为“是否可以以不破坏单例模式的方式将序列化和反序列化与单例模式类 C 一起使用?”

答案基本上是肯定的:

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 的多个实例可能使用此代码存在。但是,仅引用了一个。其他的有资格进行垃圾收集,仅由反序列化运行时创建,因此它们不存在于实际用途中。

其他两个问题的答案(在哪种情况下我们应该序列化一个单例?是否可以设计一个对象不能序列化的类?),见@Michael Borgwardt's answer .

关于java - 面试题: about Java serialization and singletons,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2958863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com