Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronization doubt  RSS feed

 
Sushanta Chakrabarty
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Tthr {
public static void main(String[]args){
TthrA t =new TthrA();
t.start();
synchronized(t){
System.out.println("waiting for t;");
try{
t.wait();}
catch(InterruptedException e){}
System.out.println("done");
}

}

}

class TthrA extends Thread{
Tthr tA = new Tthr();
public void run(){
synchronized( this){
System.out.println("b");
notify();
}
}

}

Hi, the above mentioned code is perfect. My query is what is "this" in synchronized(this)? Can you mention any other object which can replace "this"?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "this" keyword refers to the current instance of the class in which it appears. In your case, it is the current instance of class TthrA.

You can synchronise on any object. However, choosing the correct object for a particular situation is not trivial. Perhaps you should work through a good on-line tutorial or book (e.g. "Java Threads") on Java threading.

In your case, the code appears simply to be trying to demonstrate the wait() and notify() concepts. In that case, it doesn't matter too much which object you choose to synchronise on, providing that the wait() and notify() synchronise on the same object.

However, your code is not "perfect". In fact, it has at least two threading bugs in it.

  • You are not synchronised before you start the thread; this means that the notification might occur before your start waiting, in which case you'll miss it and wait forever. This is a serious error.
  • You have no protection against "spurious wakeup". All waiting threads can, in theory, get woken up by the system, rather than by a notify(). Therefore, waiting should always be done in a loop, and some shared field (or similar) should be used to allow the waiting and notifying threads to agree on whether a notification happened. This is a somewhat more arcane bug and you may choose to ignore it, while in the early stages of learning. However, you should revisit it, as it could bite you one day.


  • [ December 19, 2007: Message edited by: Peter Chase ]
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!