0

I have a java thread implementation as follows:

class MyThread extends Thread {
    private static Integer counter = 1;

    public MyThread(final String name) {
        super(name + "_" + counter);
        counter++;
    }

    @Override
    public void run() {
        try {
            sleep(0,2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(this.getName() + " true = " + true);
    }
}

And the main class as follows:

public class ThreadingTest {

    public static void main(String[] args) {
        MyThread thisThread = new MyThread("MyThread");
        thisThread.setDaemon(true);
        thisThread.start();
        try {
            Thread.sleep(0,1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

However even though the thread is sleeping for 2 nanoseconds and the calling thread is sleeping only for 1 nano second, why is my SOUT printing the statement?

Considering the fact that timeout of the called thread is more than the calling thread, shouldn't the calling thread be terminated before it can print the statement?

Shriram
  • 4,343
  • 8
  • 37
  • 64
  • you are setting the thread as daemon will cause your thread to be in background instead foreground. – Shriram Dec 04 '16 at 10:14
  • 2
    @Shriram no, that's not what setDaemon does. The notions of foreground and background don't even exist. – JB Nizet Dec 04 '16 at 10:18
  • 1
    The thread scheduler is free to schedule threads the way it wants to. And one nanosecond is a very, very small amount of time. Make the thread sleep a few millis, and you should start seeing what you expect. – JB Nizet Dec 04 '16 at 10:19
  • 3
    NEVER EVER rely on timing when it comes to threads. Many core developers tried to understand and build upon 'expected' Thread behavior. Though its literly to random to make something consistent. If you need some kind of wait/waitfor mechanism, please consider looking at the `wait` methods (provided in the Thread class) and locks (especially if resources/datastructures are involved). – n247s Dec 04 '16 at 10:25
  • I am just trying to figure out if there is a simple way to timeout a thread, that is guaranteed to work based on the timeout specified? Considering the fact that the timeout can behave erratically, if the timeouts are really small, is there another way to handle this? – dissatisfiedprogrammer Dec 04 '16 at 20:33

3 Answers3

1

Threads that are marked as daemon will be killed when all non daemon threads are finished. Therefor your thread is simply killed. What is Daemon thread in Java?

Community
  • 1
  • 1
brummfondel
  • 1,202
  • 1
  • 8
  • 11
  • This is not true. A Deamon thread will run like a nornal Thread (and will defenitly not be killed). The big difference is that a Deamon Thread doesn't prevent the JVM from exiting. It will even run for ever if its stuck in a keep-alive-loop and you don't kill it manually. – n247s Dec 04 '16 at 12:50
  • So all posts in the linked question and even JDK doc is wrong? – brummfondel Dec 04 '16 at 14:05
0

You cannot have nanosecond precision with Thread.sleep(). Even executing those instructions will take more than a nanosecond. Try your code with miliseconds instead, and see if it works!

Lucian
  • 181
  • 1
  • 5
  • 1
    "Just tweak the numbers until it works" is horrible, horrible advice when threading. – Voo Dec 04 '16 at 11:35
  • 1
    No, the advice was about Thread.sleep() not having nanosecond resolution, which explains why the code does not work as expected. If you put miliseconds or seconds, it will work as a proof of concept. If you sholud base your application logic on this, it's of course another question (and the answer is indeed no) – Lucian Dec 04 '16 at 11:47
  • Yes and my complaint is that even if sleep had nano second accuracy this code still wouldn't be guaranteed to work. You say this would work if the OP used milliseconds. But if you try with one millisecond on different OSes, hardware configurations and software settings you'll see that there are quite a lot where this is wrong. Try 15ms and you whittle down the failures but I can still easily produce a system where the code will fail. The only right answer is that the code is broken and its behaviour unspecified – Voo Dec 04 '16 at 12:42
0

Method Thread.sleep determines only amount of time for which thread is sleeping (for how long thread is in the TIMED_WAITING state). After this time thread is removed from the set of waiting threads but still has to wait to obtain CPU time. And how long it will take is very nondeterministic parameter. You should never rely on time to determine exact sequence of threads execution.

Marcin H.
  • 51
  • 4
  • Can you please point me in the right direction if I need to determine the exact sequence of threads execution. – dissatisfiedprogrammer Dec 06 '16 at 20:49
  • You have to use synchronization mechanisms built in Java language, for example: [Semaphore](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html) or [CountDownLatch](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html) are very usefull. Read about using **synchronized** clause. It's just beginning. – Marcin H. Dec 07 '16 at 16:22