Can this Java singleton get rebuilt repeatedly in WebSphere 6?

后端 未结 10 952
清酒与你
清酒与你 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:53

    This will get only loaded once when the class is loaded by the classloader. This example provides a better Singleton implementation however, it's as lazy-loaded as possible and thread-safe. Moreover, it works in all known versions of Java. This solution is the most portable across different Java compilers and virtual machines.

    
    public class Single {
    
    private static class SingleHolder {
       private static final Single INSTANCE = new Single();
    }
    
    private Single() {
    ...load properties...
    }
    
    public static Single getInstance() {
        return SingleHolder.INSTANCE;
    }
    
    }

    The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile and/or synchronized).

提交回复
热议问题