Charlie
Charlie

Reputation: 2261

What is meant by "each JVM thread has its own program counter?"

I'm trying to understand what this statement means:

Each Java Virtual Machine thread has its own pc (program counter) register. At any point, each Java Virtual Machine thread is executing the code of a single method, namely the current method (§2.6) for that thread.

https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.5.1

I assume that the JVM thread works like any other thread - that every time that thread is scheduled to run (by say the Linux kernel) that it's "program counter" is loaded from it's task_struct data structure so from the CPU's perspective there's only a single program counter - it just gets updated by the OS everytime the OS switches threads.

Is that correct? I'm confused because that whole page seems to keep emphasizing that each JVM gets it's own PC/stack/heap etc. but I thought that was a given for any process - is the JVM somehow unique from other processes?

Upvotes: 5

Views: 1769

Answers (1)

Solomon Slow
Solomon Slow

Reputation: 27190

assume that the JVM works like any other thread

The JVM is not a thread: It is a process that has many threads.

...so from the CPU's perspective there's only a single program counter

The program counter is just one of several registers that constitute the context of a thread. Each CPU has one set of physical registers (or two sets, if it's hyperthreaded, but let's keep things simple and ignore hyperthreading.) Each CPU can therefore run exactly ONE thread at any given instant time. But...

The operating system can "switch contexts": It can save all of the registers for one thread running on a given CPU, and then load the registers with the saved registers (including the program counter) from some other thread.

In a typical desktop operating system, the operating system scheduler is invoked, maybe 100 times per second or more, to decide which threads should be running at that moment. It will switch out threads that were actually running at that moment, and switch in threads that have been waiting to run.

That way, your computer can have many more live threads than it has CPUs.

Upvotes: 7

Related Questions