Skip to content

Bug fix a race condition when Scope(useNullFieldInitialization = true) is set.#272

Merged
psteiger merged 1 commit intouber:mainfrom
rysh88:bugfix_null_field_init_concurrency_v3
Oct 2, 2025
Merged

Bug fix a race condition when Scope(useNullFieldInitialization = true) is set.#272
psteiger merged 1 commit intouber:mainfrom
rysh88:bugfix_null_field_init_concurrency_v3

Conversation

@rysh88
Copy link
Collaborator

@rysh88 rysh88 commented Oct 2, 2025

A race condition occurs when Scope(useNullFieldInitialization = true) is set. This fix ensures the correct variable is checked so the correct value is returned.

current code

Activity activity() {
    Object _activity = activity;
        if (_activity == null) {
          synchronized (this) {
            if (activity == null) { // race condition here. The activity can be non-null and return a null _activity
              _activity = appCompatActivity();
              if (_activity == null) {
                throw new NullPointerException("Factory method cannot return null");
              }
              activity = _activity;
            }
          }
        }
        return (Activity) _activity;
  }

New Code

Activity activity() {
    Object _activity = activity;
        if (_activity == null) {
          synchronized (this) {
            _activity = activity; 
            if (_activity == null) { // local variable is checked instead of the global variable
              _activity = appCompatActivity();
              if (_activity == null) {
                throw new NullPointerException("Factory method cannot return null");
              }
              activity = _activity;
            }
          }
        }
        return (Activity) _activity;
  }

@rysh88 rysh88 force-pushed the bugfix_null_field_init_concurrency_v3 branch from 74cff94 to e4729dc Compare October 2, 2025 00:18
… ensures correctness by checking the appropriate variable.
@rysh88 rysh88 force-pushed the bugfix_null_field_init_concurrency_v3 branch from e4729dc to ab16afc Compare October 2, 2025 00:34
@psteiger psteiger merged commit 4174996 into uber:main Oct 2, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants