user3363969
user3363969

Reputation: 249

Incomplete execution with join

there is some problem in this code, its not getting executing. but when i am uncommenting the finally block, its just printing the "complete" without printing "holas" , Any idea?

import java.util.ArrayList;
import java.util.List;


public class MyThread {

    /**
     * @param args
     */
    public static boolean interruptTask=false;

    public static class D extends Thread{
        public void run(){
            while(!interruptTask){
                System.out.print("Hello");
            }
        }
    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
    Thread task = new D();
    task.start();
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    interruptTask=true;
    try {
        task.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }/*finally{
        System.out.println("holas");
    }*/
    System.out.println("complete");
    }

}

Upvotes: 2

Views: 99

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

There is nothing wrong with your code, this is a bug in Eclipse.

When I run the code within Eclipse I get the behavior described by the OP. When I run the generated class file from the command line it works as expected. I suspect Eclipse is buffering the output and "forgetting" to write it out to the console window. The fact that println() works while print() doesn't supports this, but then I would have expected the final println() to cause Eclipse to see the buffer.

I also ran a test where I decreased the timeout from 5000 to 10 (milliseconds), in which case the output is correct in Eclipse.

I suspect an internal buffer in Eclipse, where it stores console output, fills up. My guess is that Eclipse is looking for \n to flush to the console window. It never sees this with the OP's original code, and when the buffer fills up Eclipse just discards additional output. Since no \n is ever written to the console buffer, it never gets displayed.

I will submit a bug on the Eclipse Bugzilla. This is a very nice testcase.

EDIT: Here's an even better testcase:

public class EclipseBug
{
    private static int count = 781;
    public static void main(String[] args)
    {
        for (int i=0; i<count; i++)
            System.out.print("hello ");
        System.out.println();
    }
}

With count = 780 it works. With count = 781 no output is produced.

Eclipse Bug Filed: https://bugs.eclipse.org/bugs/show_bug.cgi?id=443433

Upvotes: 3

Related Questions