Why study the memory model?

It’s important to understand the memory model, this is specially true for Java because Java handles its variables in a much different way than non-JVM languages. It even has special keywords like volatile which wouldn’t make sense without having a proper knowledge of how these variables take shape inside the memory.

The Java Memory Model

The above diagram shows how it looks like. As you go down from Registers to RAM, size increases, latency increases, and things get further from the processor.

Field Visibility

Whenever we talk about “visibility” - it’s in reference to visibility to among threads.

Concurrency

The visibility of writing operations on shared variables can cause problems during delays that occur when writing to the main memory due to caching in each core. This can result in another thread reading a stale value (not the last updated value) of the variable.

Field Visibility Problem is solved using volatile. In below example, if writer and reader functions are getting called simultaneously in different threads, x might be 1 in local cache of core 1 but might not have updated value in shared cache. Hence when reader loads value of x, it might load it as 0.

public class FieldVisibility {
    int x = 0;

    public void writerThread() {
        x = 1;
    }

    public void readerThread() {
        System.out.println(x);
    }
}

Happens Before Relationship

Java solves this problem using Happens Before Relationship. Whatever happened before “write of x” should be visible after “read of x”. Hence, all the changes which are visible to thread T1 before a volatile write or a synchronized unlock will be visible to thread T2 after a volatile read of the same variable or locking on the same monitor.

Consider the program below:

public class Unstoppable {

    private static boolean killSwitch;

    public static void main(String[] args) 
        throws InterruptedException {

            Thread backgroundThread = new Thread(new Runnable() {
                public void run() {
                    int i = 0;
                    while (!killSwitch)
                        i+=1
                        System.out.println("Value of i is" + i.toString());
                }
            });

            backgroundThread.start();
            TimeUnit.SECONDS.sleep(1);
            killSwitch = true;

    }
}

It never stops because the updated value of stopRequested never becomes visible to backgroundThread

java -jar Unstoppable.jar com.alivcor.Unstoppable Value of i is 1 Value of i is 2 Value of i is 3 Value of i is 4 Value of i is 5 Value of i is 6 Value of i is 7 Value of i is 8 ......87212 more lines

Java - Order of Execution

  1. Static initialization blocks will run whenever the class is loaded first time in JVM
  2. Initialization blocks run in the same order in which they appear in the program.
  3. Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces.
class FileReader { 
  
    FileReader(String filePath) 
    { 
        System.out.println("Reading file with file path"); 
    } 
  
    FileReader() 
    { 
        System.out.println("Read file with no path"); 
    } 
  
    static
    { 
        System.out.println("This gets called 1st"); 
    } 
  
    { 
        System.out.println("This gets called 3rd"); 
    } 
  
    { 
        System.out.println("This gets called 4th"); 
    } 
  
    static
    { 
        System.out.println("This gets called 2nd"); 
    } 
  
    public static void main(String[] args) 
    { 
        new FileReader(); 
        new FileReader(8); 
    } 
} 
This blog post is part of the Advanced Java Series. Continue here learning Process & Threads.

Feeling generous ? Help me write more blogs like this :)


Feeling even more generous ?

$20 can feed a poor child for a whole year. Akshaya Patra (Aak-sh-ayah pa-tra) is the world’s largest NGO school meal program, providing hot, nutritious school lunches to over 1.8 million children in 19,257 schools, across India every day. Your 20$ makes all the difference.