private static final Object LOCK = new Object(); private static volatile Singleton instance; public static Singleton getInstance() { Singleton result = instance; if (result == null) { synchronized (LOCK) { result = instance; if (result == null) { instance = result = new Singleton(); } } } return result; }區域變數 result 看起來是不必要的,但在某些版本的JVM,可以提升執行效率
參考
http://en.wikipedia.org/wiki/Double-checked_locking
http://zh.wikipedia.org/wiki/%E5%8F%8C%E9%87%8D%E6%A3%80%E6%9F%A5%E9%94%81%E5%AE%9A%E6%A8%A1%E5%BC%8F
https://github.com/resteasy/Resteasy/blob/master/jaxrs/jaxrs-api/src/main/java/javax/ws/rs/ext/RuntimeDelegate.java
0 comments:
Post a Comment