反序列化对象图时,hashCode()中的NullPointerException

时间:2014-11-17 10:57:48

标签: java hashmap deserialization hashcode

我在Java类中有一个final字段,肯定会被初始化。当我序列化和反序列化相应的对象图时,我得到一个NPE,因为该字段在hashCode()方法中使用但显然还没有回读。我创建了一个最小的测试用例,其中还包含serialize() / deserialize()方法(如果这些方法有问题),但我似乎无法理解(基础)问题是什么或者如何解决它。

public class TestSerializerTest {

private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestSerializerTest.class);

private File workDir;

@Before
public void setUp() {
    workDir = new File("target/tmp");
}

@After
public void tearDown() {
    workDir.delete();
}

private static class ManagingContainer implements Serializable {

    private static final long serialVersionUID = 1L;

    private final Set<Contained> containedElements = new HashSet<Contained>();

    public Contained getContained(List<String> descriptors) {
        Contained contained = new Contained(this, descriptors);
        containedElements.add(contained);
        return contained;
    }
}

private static class Contained implements Serializable {

    private static final long serialVersionUID = 1L;

    @SuppressWarnings("unused")
    private final ManagingContainer container;
    private final List<String> descriptors;

    Contained(ManagingContainer container, List<String> descriptors) {
        this.container = container;
        if (descriptors == null) {
            throw new NullPointerException();
        }
        this.descriptors = new ArrayList<String>(descriptors);
    }

    @Override
    public int hashCode() {
        return descriptors.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (other == null || !(other instanceof Contained)) {
            return false;
        }
        return this.descriptors.equals(((Contained) other).descriptors);
    }
}

private static class OtherContainer implements Serializable {
    private static final long serialVersionUID = 1L;

    private final ArrayList<Contained> containedElements = new ArrayList<Contained>();

    public OtherContainer(Contained initialElement) {
        this.containedElements.add(initialElement);
    }

    public void addContained(Contained nextElement) {
        containedElements.add(nextElement);
    }
}

void serializeObjectToFile(Serializable serializable, File file) {
    logger.info("Saving object '{}' to file '{}'.", serializable, file.getAbsolutePath());
    ObjectOutputStream stream = null;
    try {
        if (!file.getParentFile().exists()) {
            logger.info("Creating directory '{}'.", file.getParentFile().getAbsolutePath());
            file.getParentFile().mkdirs();
        }
        stream = new ObjectOutputStream(new FileOutputStream(file));
        stream.writeObject(serializable);
        stream.flush();
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException exc) {
                logger.error("Error closing stream.", exc);
            }
        }
    }
}

Object deserializeObjectFromFile(File file) {
    ObjectInputStream oiStream = null;
    try {
        logger.info("Loading object from file '{}'.", file.getAbsolutePath());
        oiStream = new ObjectInputStream(new FileInputStream(file));
        return oiStream.readObject();
    } catch (Exception exc) {
        logger.error("Exception loading object from file '{}'. Ignoring file!", file.getAbsolutePath(), exc);
        throw new RuntimeException(exc);
    } finally {
        if (oiStream != null) {
            try {
                oiStream.close();
            } catch (IOException exc) {
                logger.error("Error closing stream.", exc);
            }
        }
    }
}

@Test
public void testSerializeDeserialize() {
    ManagingContainer container = new ManagingContainer();
    OtherContainer serializable = new OtherContainer(container.getContained(new ArrayList<String>()));
    serializable.addContained(container.getContained(new ArrayList<String>()));
    File file = new File(workDir, "test.ser");
    serializeObjectToFile(serializable, file);
    OtherContainer result = (OtherContainer) deserializeObjectFromFile(file);
}
}

执行此测试会创建以下NullPointerException

java.lang.NullPointerException: null
at TestSerializerTest$Contained.hashCode(TestSerializerTest.java:67) ~[test-classes/:na]
at java.util.HashMap.put(HashMap.java:372) ~[na:1.6.0_29]
at java.util.HashSet.readObject(HashSet.java:292) ~[na:1.6.0_29]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_29]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_29]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_29]
at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_29]
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1848) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328) ~[na:1.6.0_29]
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1946) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1870) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328) ~[na:1.6.0_29]
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1946) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1870) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350) ~[na:1.6.0_29]
at java.util.LinkedList.readObject(LinkedList.java:964) ~[na:1.6.0_29]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_29]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_29]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_29]
at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_29]
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1848) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328) ~[na:1.6.0_29]
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1946) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1870) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328) ~[na:1.6.0_29]
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350) ~[na:1.6.0_29]
at TestSerializerTest.deserializeObjectFromFile(TestSerializerTest.java:128) [test-classes/:na]
at TestSerializerTest.testSerializeDeserialize(TestSerializerTest.java:151) [test-classes/:na]

据我了解序列化,这应该不是问题(另请参阅Does Java Serialization work for cyclic references?https://softwareengineering.stackexchange.com/questions/151055/what-happens-if-we-serialize-and-deserialize-two-objects-which-references-to-eac)。

目前我不知道如何继续。任何提示都非常感谢!谢谢!

2 个答案:

答案 0 :(得分:4)

问题似乎是由ManagingContainer和Container之间的循环关系引起的。当反序列化Container时,它反过来反序列化&#39;容器引用的ManagingContainer。属性。但是,在反序列化时,它会尝试使用正在反序列化的Container填充HashSet。

如果序列化/反序列化而不是您的ManagingContainer,它应该可以正常工作,因为在调用hashCode()之前容器将被完全加载。或者,重新考虑对象图以删除循环依赖关系或编写自定义对象读/写方法。

答案 1 :(得分:1)

我遇到了一个复杂的对象图,该图具有使用HashMaps的双向圆形引用。由于在调用hashCode()时HashMap的键尚未完全加载,所以我还得到了NullPointerException:

private String id;

int hashCode() {
    return id.hashCode(); // NPE during deserialization
}

我也通过将hashCode int本身进行缓存和序列化来“解决”(阅读:“避免”)该问题:

private String id;
private int hashCode;

public void setId( String id ) {
  this.id = id;
  this.hashCode = id.hashCode();
}

public int hashCode() {
  return this.hashCode;
}

原语在序列化过程中内联。它们会在任何对象引用(例如上面的id字符串)之前立即加载。因此,即使未加载任何引用的对象,hashCode int仍然可用。

坏消息,这确实意味着,只要提供hashCode的Object都需要更新hashCode。对于具有明确定义的访问/更新的对象(例如不可变的字符串),这非常简单(请参见上面的setId(...))。对于具有复杂交互作用的对象(例如集合),这很难控制,因为它可能取决于对集合内容的更改以及集合中各个对象的hashCode的更改。

好消息,只要内存便宜,那么如果重复调用hashCode(),可能会导致性能略有改善。