Java – the transient final field used as a lock is null

The following code throws a 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);
            }
        }
    }
}

This is the output:

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)

How can the lock be empty?

Solution

The transient final field used as a lock is empty

Here are some facts about transient variables:

– when using the transient keyword on an instance variable, the instance variable is prevented from being serialized

– transient variables reach their default values during deserialization

For example:

>Object reference variable is null > int to 0 > Boolean to false, etc

That's why you get NullPointerException when deserializing

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>