Variable access

Now that we can start threads and create code that runs parallel, it is time to talk a little bit about how these threads can exchange data between each other. At first glimpse, it seems fairly simple. The threads use the same shared memory; therefore, they all can read and write all the variables that the Java access protection allows them. This is true, except that some threads may just decide not to read the memory. After all, if they have just recently read the value of some variable, why read it again from the memory to the registers if it was not modified? Who would have modified them? Let's see the following short example:

package packt.java9.by.example.thread; 

public class VolatileDemonstration implements Runnable {
private Object o = null;
private static final Object NON_NULL = new Object();
@Override
public void run() {
while( o == null );
System.out.println("o is not null");
}
public static void main(String[] args)
throws InterruptedException {
VolatileDemonstration me = new VolatileDemonstration();
new Thread(me).start();
Thread.sleep(1000);
me.o = NON_NULL;
}
}

What will happen? You may expect that the code starts up, starts the new thread, and one minute, when the main thread sets the object to something not null, will it stop? It will not.

It may stop on some Java implementations, but in most of them, it will just keep spinning. The reason for that is that the JIT compiler optimizes the code. It sees that the loop does nothing and also that the variable will just never be non-null. It is allowed to assume that because the variables not declared volatile are not supposed to be modified by any other thread, the JIT is eligible to optimize. If we declare the Object o variable to be volatile (with the volatile keyword), then the code will stop.

In case you try to remove the call to sleep, the code will also stop. This, however, does not fix the issue. The reason is that JIT optimization kicks in only after about 5000 loops of the code execution. Before that, the code runs naive and stops before the optimization will eliminate the extra and regularly not needed access to the non-volatile variable.

If this is so gruesome, then why don't we declare all variables to be volatile? Why does Java not do that for us? The answer is speed, and to understand it deeper, we will use our metaphor, the office, and the bureaucrat.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.162.49