Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is thread context switching done?

As I understand that in process context switching the OS 'backups' the registers and instruction pointer (also part of register).

But in case of switching among threads within a process will the OS take backup of the full register memory and stack?

The reason I ask this is to understand if the volatile keyword of Java is of any significance in case of single core processors.

like image 647
AppleGrew Avatar asked Dec 31 '10 09:12

AppleGrew


2 Answers

if the volatile keyword of Java is of any significance in case of single core processors.

The optimization used by the jit compiler may cause unexpected behavior.

static boolean foo = true;

public void bar(){
   while(foo){
     //doSomething
     //do not modify foo in here
   }
}

this may be optimized, since foo is not changed within the loop.

public void bar(){
    while(true){
     //Now this loop never ends
     //changes to foo are ignored
    }
}

making foo volatile will tell the jit compiler that foo can be changed by a different thread and access to it should not be optimized.

This is valid behavior since cross thread access is only guaranteed to work with

  • volatile and synchronized keywords
  • classes which state to be threadsafe (for example java.util.concurrent.*)

Update

The volatile keyword does not influence context switching itself, however it influences how reads and writes of variables are optimized. This not only influences the use of the cpu cache (important for multi-core systems) but also the optimizations used by the just in time compiler as seen above (important on all systems).

like image 164
josefx Avatar answered Oct 01 '22 14:10

josefx


understand if the volatile keyword of Java is of any significance in case of single core processors.

This line of thinking is unwise. You should program in accordance with the (documented) definition of the API and the virtual machine. You should not rely on something (in this case, the effect of volatile) having a particular effect or lack of effect that is not part of its documented definition. Even if experiment suggests it has particular behaviour in particular circumstances. Because it will bite you.

like image 41
Raedwald Avatar answered Oct 01 '22 16:10

Raedwald