Skip to main content
gamedev.net
🔒 Locked

[java] Threads and sync?

Started by bilsa Dec 12, 2005 at 5:11 AM 2 replies 750+ views
Original Post
bilsa
bilsa
Hey guys! I thought I could do a nifty invoke function for a thread, which could be used by other threads to invoke functions as they were owned by that thread:

//This is a sync object just to make the current thread
//wait until the task has been completed by the targeted
//thread
final Object syncObj = new Object();						
synchronized (syncObj) {
	//make a task to be performed later on by the targeted
	//thread
	Runnable 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 performed
	this.invoke(closeChannelTask);
	try {
		syncObj.wait();
	} catch (InterruptedException e) {}
}
//Task was executed

But whenever I try calling this function in a situation like this: 1. Tread1 calls the function on Thread2 2. The task is pushed into Thread2's task pool and Thread1 waits for completion 3. Thread2 executes all the tasks given by other threads 4. Thread2 executes the task given by Thread1 now 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?
Whackjack
Whackjack
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.
bilsa
bilsa
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 executed
before the closeChannelTask is executed.

Whackjack
Whackjack
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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.