So here is the piece of code from EventBus getDefault() static method which returns static instance of EventBus class.
/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
EventBus instance = defaultInstance;
if (instance == null) {
synchronized (EventBus.class) {
instance = EventBus.defaultInstance;
if (instance == null) {
instance = EventBus.defaultInstance = new EventBus();
}
}
}
return instance;
}
I see that code first checks if instance is null and then in synchronized block again does the same check once more. Why is that.
What if I write it like this.
/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
EventBus instance = defaultInstance;
if (instance == null) {
synchronized (EventBus.class) {
instance = EventBus.defaultInstance = new EventBus();
}
}
return instance;
}
Is there something wrong with my version? What I am missing here?