I am dealing with a race condition, I believe, in my JAVA GUI.
I have some methods that create an “anonymous method” inside an anonymous class like this:
synchronized foo()
{
someMethod(new TimerTask()
{
public synchronized run()
{
//stuff
}
};
}
QUESTION: is that run method synchronized on the TimerTask object or the class that foo is in?
QUESTION2: if I got rid of the “synchronized” in the run() declaration, and instead have a synchronized(this) {} block inside the run() body, would “this” refer to the TimerTask object or to the object that is an instance of the method that contains foo()?
Please help me out here.
Thanks,
jbu
The
runmethod is synchronized on theTimerTaskitself. Synchronized instance methods are always synchronized onthisobject. (Class methods are synchronized on theClassobject.)If you want to synchronize on the object of which
foois a member, you need to qualify thethiskeyword. Supposefoo()is a member of theBarclass, inside therun()method ofTimerTask, you can use