简体   繁体   English

Java 7中的静态初始化

[英]Static initialization in java 7

I have a code which initializes a class as: 我有一个将类初始化为的代码:

private static MyClass myObj = new MyClass();

And I am using myObj in my code below. 我在下面的代码中使用myObj This works fine if Java 6 is used . 如果使用Java 6,则可以正常工作 But when I use Java 7, NullPointerException is thrown. 但是,当我使用Java 7时,会抛出NullPointerException

java.lang.NullPointerException
Exception in thread "main" java.lang.ExceptionInInitializerError

As a work around, I put a null check for myObj before using it and made it work. 解决方法是,在使用myObj之前先对其进行空检查,然后使其myObj

But I am still confused if there is any changes in Java 7 implementation that made static initialization fail? 但是我仍然很困惑Java 7实现中是否有任何使静态初始化失败的更改?

EDIT : Found similar issue was faced by OpenAM . 编辑 :发现OpenAM面临类似的问题。

We'll need more code sample and exception stacktrace to diagnostic. 我们将需要更多代码示例和异常stacktrace进行诊断。

Pure speculation, I know that in Java 7, they changed class initialization a little bit 纯粹的猜测,我知道在Java 7中,他们稍微改变了类的初始化

https://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2 https://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2

For each class or interface C, there is a unique initialization lock LC. 对于每个类或接口C,都有一个唯一的初始化锁LC。 The mapping from C to LC is left to the discretion of the Java Virtual Machine implementation. 从C到LC的映射由Java虚拟机实现决定。 The procedure for initializing C is then as follows: 然后,初始化C的过程如下:

  1. Synchronize on the initialization lock, LC, for C. This involves waiting until the current thread can acquire LC. 在初始化锁LC上为C同步。这涉及等待直到当前线程可以获取LC。

this is different from previous java where the class object itself is used as the lock. 这与以前的java不同,在java中,类对象本身用作锁。

Still, it's quite unlikely that it's responsible for your case. 不过,它不太可能对您的案件负责。

You could try: 您可以尝试:

public class X {

   private static MyClass myObj;

   static {
      myObj = new MyClass();
   }

}

Altough the static method is usually used to perform multiple operations 通常,静态方法通常用于执行多种操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM