qxc
qxc

Reputation: 121

thread state java

I'd like to check if my reasoning is correct.

First of all, I should provide a few details about the problem I'm trying to solve. A thread (part of a program) does the following things:

  1. it starts
  2. it calls Thread.sleep (20ms)
  3. it calls getIn() method
  4. it tries to get a lock (lock.lock())
  5. if successfully gets the lock it calls Thread.sleep (100ms)
  6. if the lock is not available it calls waitingCond.await()
  7. after calling Thread.sleep (100ms) it calls lock.unlock()
  8. it calls another method getOut()
  9. it terminates (thread.join())

Given that, the following is my guessing about the thread state:

  1. READY TO RUN state
  2. TIMED WAITING state
  3. WAITING state
  4. WAITING state
  5. BLOCKED state
  6. WAITING state
  7. WAITING state
  8. TERMINATED state

Thanks

Upvotes: 5

Views: 4162

Answers (1)

Konrad Reiche
Konrad Reiche

Reputation: 29493

First of all, the state you describe with READY TO RUN is actually RUNNABLE. For my bachelor thesis I had created a transition graph showing the different thread states and when they ought to change. You haven't described the semantics of getIn(), so I guess it is just a random method.

If the thread is executing code, for instance on of your methods getIn() or getOut() it is RUNNABLE and not WAITING. BLOCKED is actually only a very short transition state, which is always entered when a thread tries to claim a lock. If the lock is not available the thread keeps being blocked and cannot execute another action as you imply in step 6. Also it cannot invoke a method after calling Thread.sleep() it has to wait, until the time is elapsed.

I would correct it the following way:

  1. RUNNABLE
  2. TIMED WAITING
  3. RUNNABLE
  4. BLOCKED
  5. TIMED WAITING
  6. BLOCKED
  7. RUNNABLE
  8. TERMINATED

Thread State Transitions

Disclaimer: There is no guarantee for the transitions. It might even be, that a JVM vendor decides to implement the underlying mechanics in another way, for instance it could implementing blocking by spin-waiting.

If you want to dive deeper into this topic use a Profiler to find out the states of your thread. I have written one of my own to detect those states: Java Concurrency Profiler, but there are others out there as well, for instance VisualVM or YourKit.

Upvotes: 11

Related Questions