   [java] Threads and sync?
  Hey guys!I thought I could do a nifty invoke function for a thread, which couldbe used by other threads to invoke functions as they were owned bythat thread://This is a sync object just to make the current thread//wait until the task has been completed by the targeted//threadfinal Object syncObj = new Object();synchronized (syncObj) {//make a task to be performed later on by the targeted//threadRunnable closeChannelTask = new Runnable() {public void run(){/*try {channel.close();} catch( IOException e) {}*/syncObj.notify();}};//This will add the task to a list, and when the targeted//thread runs again... this task will be performedthis.invoke(closeChannelTask);try {syncObj.wait();} catch (InterruptedException e) {}}//Task was executedBut whenever I try calling this function in a situation like this:1. Tread1 calls the function on Thread22. The task is pushed into Thread2's task pool and Thread1 waits for completion3. Thread2 executes all the tasks given by other threads4. Thread2 executes the task given by Thread1now I would expect everything to go fine, but I get an exception:"Current thread not owner" on the "syncObj.notify()"but that's why I made the syncObj "final" right??Anyone had a similar problem?   
  The problem is that your initial thread still has a lock on syncObj when you invoke the new thread. This lock isn't released until the wait() method is called, which is after the call to start up the new thread.  As far as I know, this will lead to unpredictable behavior.  There is a small possibility that the thread scheduler will get to the wait() method before jumping into the new thread.Your call to syncObj.notify() needs to be synchronized as well.  This should cause the thread to wait until that object is released, giving the first thread time to enter the wait() method.   ;  Nono, the invoke(Runnable) function just adds the runnable to the taskpool...so the task actually isn't executed until later, so the wait is executedbefore the closeChannelTask is executed.;  Regardless of when either of those threads are allotted execution time, you still need to acquire a lock on syncObj.Oh, and the reason you needed to make the object final is because it's method-local.  See this page