Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronization doubt

 
Animesh Shrivastava
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic