'Can double checked locking be abstracted/simplified?

My company uses double checked locking all over the place in our code. Because it is so pervasive - and so verbose - I was wondering if there is a good way to abstract it or simplify it.

For example, would a utility method like this have any problems?

    public static <T> T doubleCheckedLocking(Object lockObject, Supplier<Boolean> check, Supplier<T> task, Supplier<T> defaultValueSupplier) {
        if (check.get())
            synchronized (lockObject) {
                if (check.get())
                    return task.get();
            }
        return defaultValueSupplier.get();
    }

With that it should be possible to convert common code like:

class MySingleton {
    static volatile MySingleton instance;

    private MySingleton() { /*...*/ }

    static MySingleton instance() {
        if (instance == null) {
            synchronized (MySingleton.class) {
                if (instance == null) {
                    instance = new MySingleton();
                }
            }
        }
        return instance;
    }
}

to:

class MySingleton {
    static volatile MySingleton instance;

    private MySingleton() { /*...*/ }

    static MySingleton instance() {
        return doubleCheckedLocking(MySingleton.class, () -> instance == null, () -> {
            instance = new MySingleton();
            return instance;
        }, () -> instance);
    }
}

Are there any problems with this approach? Are there any libraries or alternatives that might do this already?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source