Singleton

class Solution {
    /**
     * @return: The same instance of this class every time
     */
     
    //http://www.cnblogs.com/EdwardLiu/p/4443230.html  


    private static Solution solInstance = null; 
    private Solution(){} //constructor 
    public static Solution getInstance() {
        // write your code here
        if (solInstance == null){
            synchronized(Solution.class){
                if(solInstance == null){
                    solInstance = new Solution(); 
                }
            }
        }
        return solInstance;
    }
};

The first 'solInstance == null' checking is to ensure the instance only be created once. However, when there are more than one threading doing the checking at the same time, it could not garantee that only one instance will be created. So synchronized is used here. The second 'solInstance == null' checking is to making sure that only the first threading could create the instance. Please see the explanation at http://www.cnblogs.com/EdwardLiu/p/4443230.html

posted on 2015-12-01 09:35  codingEskimo  阅读(147)  评论(0)    收藏  举报

导航