简体   繁体   中英

Synchronized method called by Android Activity onCreate method

Is the following situation poor design or am I overlooking something important?

Here is the code

public class MainActivity extends AppCompatActivity … {

  …

  @Override
  public void onCreate(Bundle savedInstanceState){
     …
     buildGoogleApiClient();
  }

  /**
   * Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
   */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
}

Why is buildGoogleApiClient synchronized when it's ever only called from inside onCreate ?

I know it cannot hurt, but that's hardly the point of the question. What I need to know is: Why is it necessary?

Edit

source to full code: https://github.com/googlesamples/android-play-location/blob/master/BasicLocationSample/app/src/main/java/com/google/android/gms/location/sample/basiclocationsample/MainActivity.java

In this case, synchronized will lock the object for the duration of the call. If there are other methods also declared synchronized , then only one of them will be executing at any given time. For example, if mGoogleApiClient is accessed from a synchronized method on another thread, the synchronization will ensure that the other thread either sees a fully-constructed object, or a null reference.

Even with that, you can still make a case that it's a poor implementation. A better approach would be to have each method synchronize on a private object, so that code outside the class can't inadvertently lock the object and cause unexpected behavior. OTOH, it can be argued that synchronized methods are nicer for examples because there's fewer lines of code and it's plain that the synchronization applies to the entire method.

In this particular case, volatile might have worked, though I'm not sure how that plays out with the builder pattern.

In any event, you'd need to know more about the ... sections of code to know if synchronization is necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM