File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes What must a thread keep track of? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "What must a thread keep track of?" Watch "What must a thread keep track of?" New topic

What must a thread keep track of?

Rajiv Chelsea
Ranch Hand

Joined: Jun 15, 2010
Posts: 88
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

Joined: Oct 01, 2001
Posts: 2968

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

Joined: Jun 15, 2010
Posts: 88
Anybody who can shed more light on this
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

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?

I agree. Here's the link:
subject: What must a thread keep track of?
It's not a secret anymore!