Can this Java singleton get rebuilt repeatedly in WebSphere 6?

后端 未结 10 938
清酒与你
清酒与你 2021-02-13 13:26

I\'m trying to track down an issue in our system and the following code worries me. The following occurs in our doPost() method in the primary servlet (names have been changed

10条回答
  •  盖世英雄少女心
    2021-02-13 13:32

    There is absolutely no difference between using a static initializer and lazy initialization. In fact it's far easier to mess up the lazy initialization, which also enforces synchronization. The JVM guarantees that the static initializer is always run before the class is accessed and it will happen once and only once.

    That said JVM does not guarantee that your class will be loaded only once. However even if it is loaded more than once, your web application will still see only the relevant singleton, as it will be loaded either in the web application classloader or its parent. If you have several web application deployed, then firstTime() will be called once for each application.

    The most apparent things to check is that firstTime() needs to be synchronized and that the firstTime flag is set before exiting that method.

提交回复
热议问题