File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes sleep() and GC Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "sleep() and GC" Watch "sleep() and GC" New topic

sleep() and GC

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi, this is the class and bottom the comments:
class Test extends Thread{
public Test(){
System.out.println("Constructor Test");
public void run(){
for(int i=0;i<3;i++){
System.out.println("Run and sleep " + i);
sleep(100); //without this sleep() the GC wait more time to clean up
catch(InterruptedException e){System.out.println("Error");}

}//end for
new Fini().start();
public void finalize(){
System.out.println("Test finalize");
Test t2 = new Test();
class Fini extends Thread{
public Fini(){
System.out.println("Constructor Fini");
public void run(){
System.gc();// System.runFinalization();
System.out.println("Call to gc");
public class Zero{
public static void main(String [] args){
Test t = new Test();
Print something like that :
Constructor Test
Run and sleep 0
Run and sleep 1
Run and sleep 2
Constructor Fini
Call to gc
Test finalize
Constructor Test
Run and sleep 0

In the last line, the second object dont finish the loop-for because the
sleep give the schedule to the Garbage Collector to clean the first object
who is the link to the second object.

So the sleep() can give a chance to the GC, if i am wrong please correct me.
else {thank to the javaranch friends. }
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Welcome to the The Ranch Jorge.
I think the reason why finalize does not complete is because the program has ended before. The threads started from the daemon g.c. thread are also daemon, thus they will not prevent the program from ending.
sleep as a way to favour g.c. ? Certainly selfish threads give no chance for others to run.
[ October 30, 2003: Message edited by: Jose Botella ]
[ October 30, 2003: Message edited by: Jose Botella ]
[ October 30, 2003: Message edited by: Jose Botella ]

SCJP2. Please Indent your code using UBB Code
I agree. Here's the link:
subject: sleep() and GC
It's not a secret anymore!