package threaddemo;

import java.util.concurrent.FutureTask;

public class SafeVolatileDemo {

    private static volatile SafeVolatileDemo SafeVolatileDemo;

    private SafeVolatileDemo() {}

    public static SafeVolatileDemo getInstance() {
        if (SafeVolatileDemo == null) {
            synchronized (SafeVolatileDemo.class) {
                if (SafeVolatileDemo == null) {
                    SafeVolatileDemo = new SafeVolatileDemo();
                }
            }
        }
        return SafeVolatileDemo;
    }

    public static void main(String[] args) {
        FutureTask<SafeVolatileDemo> t1 = new FutureTask<>(() -> SafeVolatileDemo.getInstance());
        FutureTask<SafeVolatileDemo> t2 = new FutureTask<>(() -> SafeVolatileDemo.getInstance());

        new Thread(t1).start();
        new Thread(t2).start();
        try {
            SafeVolatileDemo d1 = t1.get();
            SafeVolatileDemo d2 = t2.get();
            System.out.println(d1 == d2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
