TutenStain / Hedgehog-Photo

A simple and easy to use photo organizer/viewer.
3 stars 1 forks source link

Make singleton-classes enum with a single instance? #13

Closed FlorianMinges closed 12 years ago

FlorianMinges commented 12 years ago

Seems to be the cleanest way of making it thread-safe as well.

Could look something like this:


public enum Singleton {
    INSTANCE;
    public void foo(){ ... }
}

// Usage:
Singleton.INSTANCE.foo();

as found on: http://stackoverflow.com/questions/1496609/how-to-make-a-singleton-class-threadsafe

TutenStain commented 12 years ago

Here is another way to create singelton objects in Java. This implementation should also be thread safe.

public class Singleton {

private static final Object instance = new Object();

protected Singleton() {}
public static Object getInstance() {
    return instance;
}

}

This way we do not have to rewrite any of our existing classes that uses our singelton objects.

FlorianMinges commented 12 years ago

What if two threads would try to access the Singletons getInstance()-method at the same time the first time?? This could ultimately result in that two instances of the class are made.

On the other hand, this is most unlikely to happen, and I'm pretty sure our program will never ever be there (and even if it would happen, what could possibly get wrong? An error-cast due to the final-modifier on the instance-object?)