0

Recently I've been learning Android from Beginning Android games when I came across this code:

    MediaPlayer mediaPlayer;
    boolean isPrepared = false;
    public AndroidMusic(AssetFileDescriptor assetDescriptor) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
                    assetDescriptor.getStartOffset(),
                    assetDescriptor.getLength());
            mediaPlayer.prepare();
            isPrepared = true;
            mediaPlayer.setOnCompletionListener(this);
        } catch (Exception e) {
            throw new RuntimeException("Couldn't load music");
        }
    }
    public void dispose() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
        mediaPlayer.release();
    }
    public boolean isLooping() {
        return mediaPlayer.isLooping();
    }

    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public boolean isStopped() {
        return !isPrepared;
    }
    public void pause() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
    }
    public void play() {
        if (mediaPlayer.isPlaying())
            return;
        try {
            synchronized (this) {
                if (!isPrepared)
                    mediaPlayer.prepare();
                mediaPlayer.start();
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void setLooping(boolean isLooping) {
        mediaPlayer.setLooping(isLooping);
    }

    public void setVolume(float volume) {
        mediaPlayer.setVolume(volume, volume);
    }
    public void stop() {
        mediaPlayer.stop();
        synchronized (this) {
            isPrepared = false;
        }
    }
    public void onCompletion(MediaPlayer player) {
        synchronized (this) {
            isPrepared = false;
        }
    }
}

I'm very confused as to why we need to synchronize things here. Will there be more than one thing accessing these synchronized blocks? The book states, " The method OnCompletionListener.onCompletion() might be called in a separate thread, and since we set the isPrepared member in this method, we have to make sure that it is safe from concurrent modifications. " CallBacks are new to me, but I assume that when the MediaPlayer finishes, onCompletion is called. How will this onCompletion be called from a separate thread? Won't it be called on the thread that's executing this class? Eg, Thread 1 is executing play() and eventually the file ends, so onCompletion() is called on Thread 1. How will this be called on Thread 2? The synchronization on onCompletion() confuses me most, as with the other ones I somewhat understand that a different thread(UI thread) might edit the value of isPrepared in stop(), so that needs to be synchronized. The book's explanation further confuses me. How does this synchronization work, and what purpose does it serve?

2 Answers 2

0

All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.

Will there be more than one thing accessing these synchronized blocks? It's your choice. You could have a central AndroidMusic class, and request to play something from threads.

YourClass.java

  AndroidMusic androidMusic;
  public void initialize(){
    Thread thread = new Thread( 
      Runnable runnable = new Runnable() {
            @Override
            public void run() {
                androidMusic = new AndroidMusic(myAssetDescriptor);
            }
        };
    );
    thread.start();
  }

  public void playMusic(){
    Thread thread = new Thread( 
      Runnable runnable = new Runnable() {
            @Override
            public void run() {
                androidMusic.play();
            }
        };
    );
    thread.start();
  }

The strategy in this code is useful because you are using the method prepare(). This method is not async, so the UI can be blocked on the execution if is not called from a thread.

Assuming that you have the execution of the player in threads you could have concurrent request trying to modify the isPrepared at the same time. With the synchronized block all the threads will be waiting for his turn to access or modify the value.

About the onCompletion listeners: The listener of the MediaPlayer is referencing the self instance of the AndroidMusic class.

  • You initialize a new AndroidMusic();

  • You have a MediaPlayer with a Callback to self class (AndroidMusic)

The callback will be in the same thread that the AndroidMusic instance is. With the synchronized block your AndroidMusic class will be safe when a multiple threads request the play action at same time.

0

In simple term, the synchronized access can be thought of sequential access. For eg: If there is a variable which can be modified by two different methods running in two different threads without synchronized access, there might be high chance that :

  1. The change made by one Thread in that variable is not seen by the other Thread.
  2. The other Thread starts the modification taking the half-changed values of the variable done by the first Thread.

Such part of the method are called Critical Region of the method and basically, with synchronized keyword, if a Thread accesses that variable, it applies lock on that variable before going to Critical Region so, other Thread cannot access it simultaneously. It helps to prevent weird modifications.

Now, talking about MediaPlayer, there are two versions of preparing the MediaPlayer object: prepare(suitable for local files) and prepareAsync()(suitable for remote files). The Async version returns immediately without blocking the UI thread and does its background processing in a new Thread. When prepareAsync() is completed in that new Thread, a callback is returned to the Main Thread. We can set a listener for such callback via setOnPreparedListener(OnPreparedListener listener). Other than that, normally, the MediaPlayer instance is created and managed in the MainThread(UI Thread) so, there in no need of synchronized keyword. But, as @Ariel Perez said, it's always your choice and you can have two separate threads: one for setting data source on the player object and another for starting the playback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.