Results 1 to 6 of 6
Like Tree1Likes
  • 1 Post By jim829

Thread: Concurrency - why doesn't this if block execute?

  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    7

    Default Concurrency - why doesn't this if block execute?

    In the following example, a thread (the messageLoopThread) which prints four different strings, each after a sleep (Thread.sleep(4000)) of 4 seconds, is started. As long as that thread is alive (messageLoopThread.alive()), we keep waiting (messageLoopThread.join()) for 1 second and then checking if it is still alive and if it has taken more time than 3 seconds(the 'patience' variable), and if true, we interrupt (messageLoopThread.interrupt()) it.

    The problem is that since the messageLoopThread should be taking more than 16 seconds (4 seconds before printing each string), the if block for if (messageLoopThread.isAlive() && (System.currentTimeMillis() - startTime) > patience) should be executed more than once, and "Waited for a second, tired now, so interrupting it..." and "I have been interruped during my 4000ms (or 4 second) sleep period." should be printed in the output.

    But it is not executed even once, as you can see in the output in the end. The question is why?


    Java Code:
    public class SimpleThreadsExample {
    
        /**
         * Displays a message, preceded by the name of the current thread.
         */
        static void threadMessage(String message) {
            Thread currentThread = Thread.currentThread();
            String threadName = currentThread.getName();
            System.out.println(threadName + ": " + message);
        }
    
        /**
         *
         */
        private static class MessageLoop implements Runnable {
            @Override
            public void run() {
                String[] importantInfo = { "Mares eat oats.", "Doves eat oats.", "Little lambs eat ivy.", "A kid will eat ivy too." };
                for (String info : importantInfo) {
                    try {
                        Thread.sleep(4000);
                    } catch (InterruptedException ie) {
                        threadMessage("I have been interruped during my 4000ms (or 4 second) sleep period.");
                    }
    
                    threadMessage(info);
                }
            }
        }
    
        /**
         * @throws InterruptedException
         *
         */
        public static void main(String[] args) throws InterruptedException {
            // We will start the messageLoopThread and then wait for it (join method) to get done with its work, in
            // intervals; i.e. we will wait for a second and then check: if messageLoopThread is still not done and if more
            // time than a specific amount of time (set beforehand, let's call it xxx), has passed since we started waiting
            // => If no and no,
            // then we will wait for another 1sec and then check again... UNTIL more time than xxx has passed since we
            // started waiting. AT THAT POINT, we will interrupt the messageLoopThread.
            // Let's set that xxx here, and let's make it half a minute.:
            long patience = 3 * 1000;
    
            System.out.println("----------------------------------------------------------");
            threadMessage("STARTING THE MessageLoop THREAD");
            System.out.println("----------------------------------------------------------");
    
            Thread messageLoopThread = new Thread(new MessageLoop());
            messageLoopThread.start();
    
            //As long as the messageLoopThread is alive
            while (messageLoopThread.isAlive()) { // INFO: A thread is alive if it has been started and not yet died.
    
                long startTime = System.currentTimeMillis();
                threadMessage("Let's wait for the messageLoopThread thread to let it get done with what it is doing...");
    
                // Wait in 1sec intervals, i.e. wait for 1 second max. (to let the messageLoopThread thread get done with
                // what it is doing) and then check if the time since we started waiting is greater than 'patience'. If yes
                // and the (messageLoopThread) thread is still alive, interrupt it.
                messageLoopThread.join(1000);
    
                if (messageLoopThread.isAlive() && (System.currentTimeMillis() - startTime) > patience) {
                    threadMessage("Waited for a second, tired now, so interrupting it...");
                    messageLoopThread.interrupt();
                }
    
                // As you can see in the exception handler of the InterruptedException in the MessageLoop, all that happens
                // is that it prints a message. So after leaving the catch block, it will continue to do what it was
                // doing (see statement after the catch block). Now we are going to wait indefinitely for messageLoopThread to complete.
                messageLoopThread.join();
            }
            
            threadMessage("FINALLY! messageLoopThread GOT DONE AND SO IT IS NO LONGER ALIVE. yayyy!");
        }
    
    }
    OUTPUT:
    Java Code:
    ----------------------------------------------------------
    main: STARTING THE MessageLoop THREAD
    ----------------------------------------------------------
    main: Let's wait for the messageLoopThread thread to let it get done with what it is doing...
    Thread-0: Mares eat oats.
    Thread-0: Doves eat oats.
    Thread-0: Little lambs eat ivy.
    Thread-0: A kid will eat ivy too.
    main: FINALLY! messageLoopThread GOT DONE AND SO IT IS NO LONGER ALIVE. yayyy!

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Concurrency - why doesn't this if block execute?

    Line 61 waits for 1000 seconds for the thread to die and then continues. Fine. But line 71 waits forever. Probably not what you wanted.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    7

    Default Re: Concurrency - why doesn't this if block execute?

    Line 61 waits for 1000 seconds for the thread to die and then continues. Fine. But line 71 waits forever. Probably not what you wanted.
    Milliseconds, not seconds. Source.

    On line 61, we wait for a second and then is the if block, inside which we interrupt the messageLoopThread. When the messageLoopThread is interrupted while is it is asleep, it throws InterruptedException, the exception handler (catch block) of which does nothing but print a message (Line 20 -24). Then the instruction/statement after the handler (the catch block) is executed.

    Even if you forget about/ignore line # 71, the question is still there. Why doesn't the string "Waited for a second, tired now, so interrupting it..." ever display in the output?

    This example is my version of this example.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Concurrency - why doesn't this if block execute?

    Hah! You're right about the seconds vs milliseconds. I forgot the prefix.

    The conditional block is never entered because the second part of the conditional is not true when it is first encountered.
    Once that block is bypassed, the next join() is invoked and waits until the thread dies (which in this case happens to be when
    the main thread exits).

    Regards,
    Jim
    Last edited by jim829; 02-05-2016 at 12:25 AM. Reason: shorter explanation
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    7

    Default Re: Concurrency - why doesn't this if block execute?

    @Jim829 You are right. Thank you for correcting me. I am clear about it now.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Concurrency - why doesn't this if block execute?

    Quote Originally Posted by Zarah View Post
    Thank you for correcting me.
    Likewise! :)

    Regards,
    Jim
    Zarah likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 3
    Last Post: 06-11-2013, 12:50 AM
  2. TASLock in concurrency
    By lovelycse in forum Threads and Synchronization
    Replies: 2
    Last Post: 01-19-2013, 06:14 AM
  3. Java in Concurrency
    By bernerd in forum Advanced Java
    Replies: 0
    Last Post: 10-03-2011, 08:20 AM
  4. A set of questions on concurrency.
    By KutaBeach in forum Threads and Synchronization
    Replies: 1
    Last Post: 07-22-2011, 04:21 PM
  5. Practicing Concurrency
    By sunde887 in forum New To Java
    Replies: 1
    Last Post: 06-21-2011, 03:27 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •