• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What must a thread keep track of?

 
Rajiv Chelsea
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read in HeadFirst Java that a thread must keep track of which statement (of which method)
is currently executing on the thread's stack..

How is it done and why is it necessary?
 
Greg Charles
Sheriff
Posts: 2989
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't have a copy of this book, but I imagine they were making a point of how little information has to be saved to switch from thread to thread in contrast with switching between processes. That's because threads share the same memory space.

How is it done? Actually, I'm not totally sure, but basically it would be something like taking the value of the program counter register out of the CPU, and probably some other register values, and storing them in the thread's local memory area. Then the thread manager could read those values back to restore the CPU state and restart the thread.

Why is it done? A thread runs its task for some specified amount of time when the thread scheduler interrupts it and gives another thread a chance to run. Eventually, the first thread gets to run again, and it needs some way to pick up where it left off.
 
Rajiv Chelsea
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anybody who can shed more light on this
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajiv Chelsea wrote:...why is it necessary?


It is necessary because the OS can switch contexts, temporarily pausing execution of the current thread from running in favor of allowing a different one run. At a later time the Thread will be re-started and needs to know precisely where it was when it was stopped because of the Context Switch.


Rajiv Chelsea wrote:How is it done...?


That is an implementation detail of the particular JVM you are running, and is not really necessary to know the details of - especially since it could be different between OSes, versions, or vendors. Why do you think you need to know how?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic