0

I am reading through some of the Android Java code, and I came across this:

public void registerObserver(T observer) {
    if (observer == null) {
        throw new IllegalArgumentException("The observer is null.");
    }
    synchronized(mObservers) {
        if (mObservers.contains(observer)) {
            throw new IllegalStateException("Observer " + observer + " is already registered.");
        }
        mObservers.add(observer);
    }
}

I have only seen synchronized used as a keyword before a variable or class. What does it do in this instance?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Max Candocia
  • 4,294
  • 35
  • 58

2 Answers2

1

In this case synchronized means accessing the data of mObservers with some sort of locking to ensure thread safety. Other threads cannot access mObservers until the current thread finished with the synchronized block.

Check out this documentation.

earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
1

If any other thread encounters a synchronized(mObservers) in this member function or any other member function whilst a particular thread is inside the synchronized block above, then that thread will halt until the particular thread has exited block.

This can be useful if mObservers can only be changed by one thread at any time, and is a finer-grained synchronization technique than synchronizing on a class or instance.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483