I had this code (which was working fine):
public static void runOnUiThread(Activity c, final Runnable action) {
// Check if we are on the UI Thread
if (Looper.getMainLooper() == Looper.myLooper()) {
// If we are, execute immediately
action.run();
return;
} // Else run the runnable on the UI Thread and wait
Runnable r = new Runnable() {
@Override
public void run() {
action.run();
synchronized (this) {
this.notify();
}
}
};
synchronized (r) {
try {
c.runOnUiThread(r);
r.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And I was getting Synchronization on local variable warning. As suggested, I removed the synchronization on the local variable, in order to fix the warning:
public static void runOnUiThread(Activity c, final Runnable action) {
// Check if we are on the UI Thread
if (Looper.getMainLooper() == Looper.myLooper()) {
// If we are, execute immediately
action.run();
return;
} // Else run the runnable on the UI Thread and wait
Runnable r = new Runnable() {
@Override
public void run() {
action.run();
this.notify();
}
}
try {
c.runOnUiThread(r);
r.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
And now I am getting an exception when calling this method:
06-15 09:18:13.252 27282 27282 E AndroidRuntime FATAL EXCEPTION: main
06-15 09:18:13.252 27282 27282 E AndroidRuntime java.lang.IllegalMonitorStateException: object not locked by thread before notify()
06-15 09:18:13.252 27282 27282 E AndroidRuntime at java.lang.Object.notify(Native Method)
06-15 09:18:13.252 27282 27282 E AndroidRuntime at org.matapps.android.simpleappcreator.Utils$100000007.run(Utils.java:673)
06-15 09:18:13.252 27282 27282 E AndroidRuntime at android.os.Handler.handleCallback(Handler.java:615)
06-15 09:18:13.252 27282 27282 E AndroidRuntime at android.os.Handler.dispatchMessage(Handler.java:92)
06-15 09:18:13.252 27282 27282 E AndroidRuntime at android.os.Looper.loop(Looper.java:137)
06-15 09:18:13.252 27282 27282 E AndroidRuntime at android.app.ActivityThread.main(ActivityThread.java:4867)
06-15 09:18:13.252 27282 27282 E AndroidRuntime at java.lang.reflect.Method.invokeNative(Native Method)
06-15 09:18:13.252 27282 27282 E AndroidRuntime at java.lang.reflect.Method.invoke(Method.java:511)
06-15 09:18:13.252 27282 27282 E AndroidRuntime at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
06-15 09:18:13.252 27282 27282 E AndroidRuntime at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
I'm pretty sure I need the synchronization (as the runnable runs on a different thread), but I was told local variables shouldn't have synchronization. Any tips? Thanks!