Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Thread - blocked status

I have a very basic question. If a thread is busy in IO operation why it is not considered in a RUNNING state? If the IO operation is taking long time it means that the thread is doing its work. How can a thread be called BLOCKED when it is actually doing it's work?

like image 846
user1877246 Avatar asked Nov 14 '13 15:11

user1877246


2 Answers

I don't know where you read that a thread is in the BLOCKED state when doing IO. The BLOCKED state documentation says:

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.

So, no, a thread is not in a blocked state while doing IO (unless of course reading or writing forces it to wait on an object's monitor).

like image 102
JB Nizet Avatar answered Nov 11 '22 11:11

JB Nizet


If you run the following code with a thread blocking on IO

public class Main {
    public static void main(String[] args) throws  InterruptedException {
        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // blocking read
                try {
                    System.in.read();
                } catch (IOException e) {
                    throw new AssertionError(e);
                }
            }
        });
        thread.start();
        for(int i=0;i<3;i++) {
            System.out.println("Thread status: "+thread.getState());
            Thread.sleep(200);
        }
        System.exit(0);
    }
}

prints

Thread status: RUNNABLE
Thread status: RUNNABLE
Thread status: RUNNABLE
like image 27
Peter Lawrey Avatar answered Nov 11 '22 09:11

Peter Lawrey