This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Does a thread keep its locks if it goes to sleep?

 
Jasper Vader
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
situation:
method a is synchronized, and prints out "hey!" + thread's name once .
thread one gets a lock on it.
thread one has a for loop in its run() method which wants to loop through 5 times and print out "Hey" plus thread name. but there is a call to Thread.sleep(); at the end of the synchronized method.
i read in the kathy_bert book that a thread keeps its locks when it goes to sleep - does that mean no other thread can enter the synchronized method it was doing, if it was in the middle of a series of iterations of a for loop in its run method?
 
Leandro Oliveira
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well, when there is a call to Thread.sleep(num) the current thread will sleep, and,won't release the lock, to release the lock you should call wait method on the object, in other words, just call wait if it is a synchronized instance method. If it is a synchronized class method, try Class.forName("nameOfClass").wait();

hope it helps!
 
Jasper Vader
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, thankyou leandro, i am a bit confused on this one, but, as you say, the thread will keep its locks on objects if it gets sent to sleep...
 
mohamed hamdy
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
when a thread call a synchronized static method.
Is he will lock all instansiated objects of the class?
 
Leandro Oliveira
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for each class entity you create there is an associated Class object.
public class Test{
public synchronized void m1(){
}
//can be rewriten this way:
/*
public void m1(){
synchronized(this){
// here you place code.
}
}
*/
public synchronized static void m2(){

}
//this method can be rewriten in this way:
/*
public static void m2(){
synchronized(Test.class){
}
}*/
}
remember, there is an associated class object. Take a look at documentation for java.lang.Class because synchronization on static methods has to do with instances of Class.
 
mohamed hamdy
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks leanardo, but is that important for the exam?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic