Search code examples
javamultithreadingperformancecpulow-level

Minimum Time given to a thread


My question is regarding threads in general(ex: in Java).

The problem : when a thread is being in (Runnable - state) - i.e: it is executing, and it is giving an instruction (say by invoking the method addOneToX(int x)), is it possible for the thread to quit or stop its work before finishing the instruction but after it has started executing it. in other words, most of instructions in high-level languages are decoded into the machine-specific language and decomposed to a number of machine-cycles (clock-cycles) in the CPU. So I guess it is clear, accordingly:

1> What is the minimum time given to a thread to be in the Runnable state?

2> How does the thread save its state so that it comes to it later? (i.e: when it quits Runnable state and comes back to it later to continue from where it stopped)


Solution

  • There is no guaranteed minimum time.

    The scheduler decides what the time slice will be. Usually you could expect anything from fractions of a millisecond to about 100ms. But often this value will by dynamic. Also, a thread might even encounter an extreme like running only one instruction which happens to be I/O, upon which the thread blocks and is pushed out of CPU.

    The high-level language instructions are eventually translated into (possibly) multiple CPU instructions. The CPU instruction is the atomic part that will be executed without interruption, other than that the program may be interrupted at any place between two instructions, even in the middle of a high-level language command. Note that there are some specific CPU instructions (like atomic get-and-set or get-and-increase) that can be used for thread synchronization.

    The basic (much simplified) idea of storing the thread's state is: store the registers in RAM and store the pointer to current instruction.