Search code examples
javasynchronizationclassthisanonymous

Java anonymous classes and synchronization and "this"


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 1: is that run method synchronized on the TimerTask object or the class that foo is in?

QUESTION 2: 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()?


Solution

  • The run method is synchronized on the TimerTask itself. Synchronized instance methods are always synchronized on this object. (Class methods are synchronized on the Class object.)

    If you want to synchronize on the object of which foo is a member, you need to qualify the this keyword. Suppose foo() is a member of the Bar class, inside the run() method of TimerTask, you can use

    public void run() {
      synchronized(Bar.this) {
        ...
      }
    }