本文介绍了用作锁的瞬态最终字段为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码抛出 NullPointerException

import java.io.*;

public class NullFinalTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Foo foo = new Foo();
        foo.useLock();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        new ObjectOutputStream(buffer).writeObject(foo);
        foo = (Foo) new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())).readObject();
        foo.useLock();
    }

    public static class Foo implements Serializable {
        private final String lockUsed = "lock used";
        private transient final Object lock = new Object();
        public void useLock() {
            System.out.println("About to synchronize");
            synchronized (lock) { // <- NullPointerException here on 2nd call
                System.out.println(lockUsed);
            }
        }
    }
}

这里是输出:

About to synchronize
lock used
About to synchronize
Exception in thread "main" java.lang.NullPointerException
    at NullFinalTest$Foo.useLock(NullFinalTest.java:18)
    at NullFinalTest.main(NullFinalTest.java:10)

lock 怎么可能为空?

推荐答案

用作锁的瞬态最终字段为空

以下是关于瞬态变量的一些事实:

- 在实例变量上使用时的瞬态关键字,阻止该实例变量被序列化。

- Transient keyword when used on an instance variable, will prevent that instance variable to be serialized.

- 在反序列化中,瞬态变量到达他们的默认值 .....

- On De-serialization, the transient variable get to their Default values.....

例如:


  • 对象引用变量 null

  • int到 0

  • 布尔到 false,等.......

  • Object Reference Variable to null
  • int to 0
  • boolean to false, etc.......

这就是你在反序列化时获得 NullPointerException 的原因......

So thats the reason you are getting a NullPointerException, when deserializing it...

这篇关于用作锁的瞬态最终字段为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 00:11