1. Introduction

Before we introduced thread-safety, and how it can be achieved.

In this article, we’ll take a look at local variables and why they are thread-safe.

2. Stack Memory and Threads

Let’s start with a quick recap of the JVM memory model.

Most importantly, the JVM splits up its available memory into stack and heap memory. Firstly, it stores all objects on the heap. Secondly, it stores local primitives and local object references on the stack.

In addition, it’s important to realize that every thread, including the main thread, has its own private stack. Therefore, other threads do not share our local variables, which is what makes them thread-safe.

3. Example

Let’s now continue with a small code example containing a local primitive and a (primitive) field:

public class LocalVariables implements Runnable {    private int field;     public static void main(String... args) {        LocalVariables target = new LocalVariables();        new Thread(target).start();        new Thread(target).start();    }     @Override    public void run() {        field = new SecureRandom().nextInt();        int local = 42;        System.out.println(field + ":" + local);    }}

On line five, we instantiate one copy of the LocalVariables class. On the next two lines, we start two threads. Both will execute the run method of the same instance.

Inside the run method, we update the field field of the LocalVariables class. Secondly, we see an assignment to a local primitive. Finally, we print the two fields to the console.

Let’s take a look at the memory location of all the fields.

First, the field is a field of class LocalVariables. Therefore, it lives on the heap. Secondly, the local variable number is a primitive. Consequently, it’s located on the stack.

#Java #Core Java #Java Concurrency

Why are Local Variables Thread-Safe in Java
2.45 GEEK