java - Does wait() need synchronization on local variable -
i had code (which working fine):
public static void runonuithread(activity c, final runnable action) { // check if on ui thread if (looper.getmainlooper() == looper.mylooper()) { // if are, execute action.run(); return; } // else run runnable on ui thread , 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 getting synchronization on local variable
warning. suggested, removed synchronization on local variable, in order fix warning:
public static void runonuithread(activity c, final runnable action) { // check if on ui thread if (looper.getmainlooper() == looper.mylooper()) { // if are, execute action.run(); return; } // else run runnable on ui thread , 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 getting exception when calling 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 thread before notify() 06-15 09:18:13.252 27282 27282 e androidruntime @ java.lang.object.notify(native method) 06-15 09:18:13.252 27282 27282 e androidruntime @ org.matapps.android.simpleappcreator.utils$100000007.run(utils.java:673) 06-15 09:18:13.252 27282 27282 e androidruntime @ android.os.handler.handlecallback(handler.java:615) 06-15 09:18:13.252 27282 27282 e androidruntime @ android.os.handler.dispatchmessage(handler.java:92) 06-15 09:18:13.252 27282 27282 e androidruntime @ android.os.looper.loop(looper.java:137) 06-15 09:18:13.252 27282 27282 e androidruntime @ android.app.activitythread.main(activitythread.java:4867) 06-15 09:18:13.252 27282 27282 e androidruntime @ java.lang.reflect.method.invokenative(native method) 06-15 09:18:13.252 27282 27282 e androidruntime @ java.lang.reflect.method.invoke(method.java:511) 06-15 09:18:13.252 27282 27282 e androidruntime @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:1007) 06-15 09:18:13.252 27282 27282 e androidruntime @ com.android.internal.os.zygoteinit.main(zygoteinit.java:774)
i'm pretty sure need synchronization (as runnable runs on different thread), told local variables shouldn't have synchronization. tips? thanks!
i don't know android development tools, warning sounds over-zealous. compiler trying avoid synchronizing on instance visible single thread. it's smart enough know local variable, r
, can seen 1 thread, apparently not smart enough know r
in original thread , this
in new thread both refer same instance.
i try work around problem making r
instance variable.
Comments
Post a Comment