Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a separate thread change static variable?

After surfing the web, I am still confused about the following thread behavior. I am aware that static variables are shared within the same classloader, however there's sth definitely missing in this extract:

public class parallelCounter {
    public static final int N = 100000000;
    public static int j = 0;
    public static void inc() {
        for (int i = 0; i < N; i++) {
            j++;
        }
        System.out.println(j); // 10000000
    }
}

class parallelCounterDemo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                parallelCounter.inc();
            }
        });
        t1.start();
        System.out.println(parallelCounter.j); // 0 Why?
    }
}
like image 200
Konstantin Avatar asked Jul 17 '17 12:07

Konstantin


People also ask

Are static variables changeable?

Static variables belong to the class instead of to the individual instances, so it doesn't change in every instance - it only exists in one place. It may give the appearance of changing in every instance, but that is because there is only one variable.

Is static variable shared between threads?

Static variables are indeed shared between threads, but the changes made in one thread may not be visible to another thread immediately, making it seem like there are two copies of the variable.

Can threads access static variables?

Static variable is a shared resource, which can be used to exchange some information among different threads.

Are static variables shared between threads in C?

Each thread will share the same static variable which is mostly likely a global variable. The scenario where some threads can have wrong value is the race condition (increment isn't done in one single execution rather it is done in 3 assembly instructions, load, increment, store).


1 Answers

There are two things to note here:

  1. Your code has a race-condition in that the state when printing depends on the execution speed of the two independent threads. Most times t1 will not even have started executing inc when your println executes. You might try adding a sleep(100) or something after t1.start.

  2. You have to take care that not all changes to variables made by one thread will be instantly visible to other threads - this is a pretty complex topic where you have to check which constucts will result in data-synchronization between threads. For you example the easiest way could be to declare j as public static volatile int.

like image 138
piet.t Avatar answered Sep 21 '22 14:09

piet.t