Question

If I have 10 threads or so accessing the same variable (only reading it, not writing) will java allow these to read the variable simultaneously or each thread will queue for reading?

I am interested on the standard behaviour, i.e. no special care was taken accessing the variable.

The program is running on a Linux RedHat.

Was it helpful?

Solution

Ideally, it will read it simultaneously, but it is not safe in some cases.

For example, if you declare:

int i = 1;

Thread threadOne = new Thread() {
public void run() {
    i++;
    System.out.println("ThreadOne is " + i);
}
};

Thread threadTwo = new Thread() {
public void run() {
    i++;
    System.out.println("ThreadTwo is "+ i);
}
};

Thread threadThree = new Thread() {
public void run() {
    i++;
    System.out.println("ThreadThree is " + i);
}
};

threadOne.start();
threadTwo.start();
threadThree.start();

You can try several times and you will see the result varies. Without synchronization, all of thread will read and write the memory "randomly" OR "simultaneously" in the other word, depend on who finish first.

The result I get after run the program several times:

ThreadOne is 1
ThreadThree is 3
ThreadTwo is 2

ThreadOne is 3
ThreadThree is 3
ThreadTwo is 3

ThreadTwo is 2
ThreadThree is 3
ThreadOne is 2

As we can see, all three thread read the memory which contain int i randomly and update the int a by adding one. If one thread has added one, then another thread will read 2.

The system.out.println() is also a process. In the second attempt, it prints all 3s. It means after three thread has read int i and add 1, the final result of int i became 3. Then the system.out.println will all print 3. Here is another way to prove, among all these threads, all the process are running simultaneously or the thread are running simultaneously.

OTHER TIPS

Multiple threads can read the same value if you allow it without using synchronization. Although if you are not changing the value, make sure that all 10 threads saw the latest value (perhaps the initial value) before the long period of reading (this would require synchronization at least once).

Yes the read AND write will be done simultaneously, to have more consistency you should add the volatile keyword to your variable. It still don't hold a lock, but if somehow in the future you want to do some write operations that would be more consistent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top