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
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.
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.
There are two types of thread synchronization mutual exclusive and inter-thread communication. Synchronized method. Synchronized block. Static synchronization.
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.
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) {
...
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With