Java Android: How does the Getting Users Location Concurrency work? [duplicate]

  android, java, location, synchronization

I’m new to Java and Android development. The task is to get user’s location (which was reached), I got the result of 50.28.. in variable "lat"
as far as I am trying to print this variable outside the function OnSuccess I get the value null.

Due to the lack of knowlendge I can only assume the problem is in synchronization as OnSuccess needs more time to run and till the moment of printing the text it’s still not initialized. However I’m not sure if I understand the problem correctly and would like to ask for a short explanation on how it works.

How can I use the result of OnSuccess further on in my program?

    FusedLocationProviderClient fusedLocationProviderClient;
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(mainActivity);

    Double lat = null; // variable for storing latitude

        /** If we have permission -> get location */
        if(mainActivity.getApplicationContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
            // get the location
                    .addOnSuccessListener(new OnSuccessListener<Location>() {
                        public void onSuccess(Location location) {

                            if(location != null)
                                lat = location.getLatitude(); // = 50.28...
    }; // = null

Source: Android Questions