次のコードはをスローし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
nullになる可能性がありますか?