wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronization doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronization doubt" Watch "Synchronization doubt" New topic
Author

Synchronization doubt

Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
hey all,
I have the run method in a class which is synchronized. Inside the method run() i have called a different method which is unsynchronized. Here is the program:
---------------------------------------------------------------------------
public class SynchClass {
public static void main(String[] args) {
ImpRunnable imRun = new ImpRunnable();
Thread tr1 = new Thread(imRun);
Thread tr2 = new Thread(imRun);
Thread tr3 = new Thread(imRun);
tr1.start();
tr2.start();
tr3.start();
}
}


class ImpRunnable implements Runnable {

public synchronized void run() {
try {
Thread.sleep(1000);
} catch(InterruptedException ie) {

}
for(int i = 0; i < 100; i++) {
callMe();
System.out.println(i + "time" + Thread.currentThread().getName());
}
}

void callMe() {
System.out.println("hii");
}
}
------------------------------------------------------------------------
My doubt is that whether the thread currently having the lock will still be holding the lock during the execution of the method callMe(), which is unsynchronized? and why?
mridul makkar
Greenhorn

Joined: Feb 15, 2005
Posts: 14
No as soon as it calls the callme function the lock gets opened.....I do not know the exact reason bit thats i am sure because it happened with me once.....
If some one else knows it so please tell me .....according to rules it should not release the control but it does .......WHY?
Subhash Bhushan C
Ranch Hand

Joined: Jan 27, 2005
Posts: 106
Whenever a thread enters a synchronized method in an object, it acquires the lock on an object; meaning that, no other thread can enter any of the synchronized methods in that class for that object. But, if the class has both synchronized and nonsynchronized methods, multiple threads can still access the nonsynchronized methods of the class.

No as soon as it calls the callme function the lock gets opened.....I do not know the exact reason bit thats i am sure because it happened with me once.....

The thread does not release the lock on the object, until the synchronized method execution ends. But that does not mean that, if the callMe() method is being executed by the thread from the run() method. Any other thread can independently call the callMe() method (because it is not synchronized).


Regards,<br />Subhash Bhushan.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronization doubt