samedi 2 juin 2018

Singleton how to see the thread in the method

I'm following the book Head First Design Patterns (CHAPTER 5, The Singleton Pattern).

They talk about the overlap of the thread into the method getInstance() when the synchronized keyword is not used.

How can I see, on the screen, the difference of the two behaviours of the threads?

  public class ChocolateBoiler {    

        private boolean empty;
        private boolean boiled;
        private static ChocolateBoiler chocolateBoilerInstance;

        public ChocolateBoiler() {
            empty = true;
            boiled = false;
        }

        public static (synchronized) ChocolateBoiler getInstance() {
            if (chocolateBoilerInstance == null) {
                chocolateBoilerInstance = new ChocolateBoiler();
            }
            return chocolateBoilerInstance;
        }

        public void fill() {
            if (isEmpty()) {
                empty = false;
                boiled = false;
                // fill the boiler with a milk/chocolate mixture
            }
        }

        public void drain() {
            if (!isEmpty() && isBoiled()) {
                // drain the boiled milk and chocolate
                empty = true;
            }
        }

        public void boil() {
            if (!isEmpty() && !isBoiled()) {
                // bring the contents to a boil
                boiled = true;
            }
        }

        public boolean isEmpty() {
            return empty;
        }

        public boolean isBoiled() {
            return boiled;
        }

        public static void main(String[] args) {

            ChocolateBoiler boiler = ChocolateBoiler.getInstance();
            boiler.fill();
            boiler.boil();
            boiler.drain();
        }
 }

Aucun commentaire:

Enregistrer un commentaire