Skip to content

Commit

Permalink
Android: Fix race condition in displayAlertMsg
Browse files Browse the repository at this point in the history
It was possible for sAlertMessageLock.notify() to be called before
sAlertMessageLock.wait(), causing Dolphin to deadlock. In particular,
this was guaranteed to happen if displayAlertMsg was called from the UI
thread while the emulation activity is being destroyed, because
runOnUiThread runs the passed-in anonymous function immediately when
called from the UI thread.

By replacing Object.wait/Object.notify with Semaphore.acquire/
Semaphore.release, it no longer matters what order the methods are
called in.
  • Loading branch information
JosJuice committed Apr 5, 2024
1 parent 4312840 commit 9ca9d07
Showing 1 changed file with 8 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@

import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;
import java.util.concurrent.Semaphore;

/**
* Class which contains methods that interact
* with the native side of the Dolphin code.
*/
public final class NativeLibrary
{
private static final Object sAlertMessageLock = new Object();
private static final Semaphore sAlertMessageSemaphore = new Semaphore(0);
private static boolean sIsShowingAlertMessage = false;

private static WeakReference<EmulationActivity> sEmulationActivity = new WeakReference<>(null);
Expand Down Expand Up @@ -492,15 +493,12 @@ public static boolean displayAlertMsg(final String caption, final String text,
});

// Wait for the lock to notify that it is complete.
synchronized (sAlertMessageLock)
try
{
sAlertMessageSemaphore.acquire();
}
catch (InterruptedException ignored)
{
try
{
sAlertMessageLock.wait();
}
catch (Exception ignored)
{
}
}

if (yesNo)
Expand All @@ -520,10 +518,7 @@ public static boolean IsShowingAlertMessage()

public static void NotifyAlertMessageLock()
{
synchronized (sAlertMessageLock)
{
sAlertMessageLock.notify();
}
sAlertMessageSemaphore.release();
}

public static void setEmulationActivity(EmulationActivity emulationActivity)
Expand Down

0 comments on commit 9ca9d07

Please sign in to comment.