Creating Object in a thread safety way

前端 未结 8 2385
再見小時候
再見小時候 2021-02-06 12:50

Directly from this web site, I came across the following description about creating object thread safety.

Warning: When constructing an object that will b

8条回答
  •  感动是毒
    2021-02-06 13:31

    Here is your clear example :

    Let's say, there is class named House

    class House {
        private static List listOfHouse;
        private name;
        // other properties
    
        public House(){
            listOfHouse.add(this);
            this.name = "dummy house";
            //do other things
        }
    
     // other methods
    
    }
    

    And Village:

    class Village {
    
        public static void printsHouses(){
             for(House house : House.getListOfHouse()){
                   System.out.println(house.getName());
             }
        }
    }
    

    Now if you are creating a House in a thread, "X". And when the executing thread is just finished the bellow line,

    listOfHouse.add(this); 
    

    And the context is switched (already the reference of this object is added in the list listOfHouse, while the object creation is not finished yet) to another thread, "Y" running,

    printsHouses();
    

    in it! then printHouses() will see an object which is still not fully created and this type of inconsistency is known as Leak.

提交回复
热议问题