+void *TriStateSingleton::getInstance(InstantiatorFn *instantiator, const void *context,
+ void *&duplicate,
+ UErrorCode &errorCode) {
+ duplicate=NULL;
+ if(U_FAILURE(errorCode)) {
+ return NULL;
+ }
+ // TODO: With atomicops.h: void *instance = (void*)Acquire_Load(&fInstance);
+ // and remove UMTX_ACQUIRE_BARRIER below.
+ void *instance=ANNOTATE_UNPROTECTED_READ(fInstance);
+ UMTX_ACQUIRE_BARRIER;
+ ANNOTATE_HAPPENS_AFTER(&fInstance);
+ if(instance!=NULL) {
+ // instance was created
+ return instance;
+ }
+
+ // The read access to fErrorCode is thread-unsafe, but harmless because
+ // at worst multiple threads race to each create a new instance,
+ // and all losing threads delete their duplicates.
+ UErrorCode localErrorCode=ANNOTATE_UNPROTECTED_READ(fErrorCode);
+ if(U_FAILURE(localErrorCode)) {
+ // instance creation failed
+ errorCode=localErrorCode;
+ return NULL;
+ }
+
+ // First attempt to create the instance.
+ // If a race occurs, then the losing thread will assign its new instance
+ // to the "duplicate" parameter, and the caller deletes it.
+ instance=instantiator(context, errorCode);
+ UMTX_RELEASE_BARRIER; // Release-barrier before fInstance=instance;
+ Mutex mutex;
+ if(fInstance==NULL && U_SUCCESS(errorCode)) {
+ // instance creation newly succeeded
+ U_ASSERT(instance!=NULL);
+ ANNOTATE_HAPPENS_BEFORE(&fInstance);
+ // TODO: With atomicops.h: Release_Store(&fInstance, (AtomicWord)instance);
+ // and remove UMTX_RELEASE_BARRIER above.
+ fInstance=instance;
+ // Set fErrorCode on the off-chance that a previous instance creation failed.
+ fErrorCode=errorCode;
+ // Completed state transition: initial->succeeded, or failed->succeeded.
+ } else {
+ // Record a duplicate if we lost the race, or
+ // if we got an instance but its creation failed anyway.
+ duplicate=instance;
+ if(fInstance==NULL && U_SUCCESS(fErrorCode) && U_FAILURE(errorCode)) {
+ // instance creation newly failed
+ fErrorCode=errorCode;
+ // Completed state transition: initial->failed.
+ }
+ }
+ return fInstance;