Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 486
jbu Avatar asked Apr 30 '09 22:04

jbu


People also ask

What are anonymous classes in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

What does synchronized this mean in Java?

Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.

What are the two types of synchronization in Java?

There are two types of thread synchronization mutual exclusive and inter-thread communication. Synchronized method. Synchronized block. Static synchronization.

Can we synchronize class in Java?

There is nothing preventing you from synchronizing every method of a class. If you use synchronized keyword on every method declaration that would mean that only one method of the class can execute concurrently.


2 Answers

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) {
    ...
  }
}
like image 163
erickson Avatar answered Oct 06 '22 06:10

erickson


I'm pretty sure of these answers, but I can't dig up a good source atm.

The first question:
synchronized will lock on the TimerTask.

Second question:
this refers to the TimerTask; if you wanted to lock on the containing object you'd use MyContainingObject.this

like image 38
Kevin Montrose Avatar answered Oct 06 '22 07:10

Kevin Montrose