I am struggling to understand on java threads work so excuse this rather simple question.
Let’s assume I have a program with N threads. Each thread executes the same instructions on a different part of an array of Strings. We invoke the thread through a class with a runnable interface. For the purposes of this example, let say it is something like this:
run() {
while (startStop = loopGetRange() != null) {
countLetters(startStop.start,startStop.stop);
/* start is the beginning cell in the array where the process starts
and stop is the ending cell in the array where the process stops */
}
}
Finally countLetters is just a simple method as follow:
private void countLeters (int start, int stop) {
for (int y = start; <= stop; y++) {
String theWord = globalArray[y];
int z = theWord.length;
System.out.println("For word "+theWord+" there are "+z+" characters");
}
}
Here is my question: Are variables like “theWord” and “Z” local to the thread or are they shared across the thread and are thus subject to possible thread collisions. If the latter, how best to protect these variables.
Thanks for helping a confused person.
Elliott
Local variables are allocated on the stack, and are local to the thread. Only member fields are shared across threads. So,
theWordandZare not shared across threads and you don’t need to worry about clashing.Given that a String is immutable, the only concern about thread safety we would have in method countLeters() is access to the globalArray.
Now, if the construction of this array “happened-before” the access to globalArray, the code is safe as long as no thread “writes” to the globalArray.
“happened-before” relationships can be enforced by number of ways (by using the
synchronizedkeyword,finalkeyword,volatilekeyword, usingjava.util.concurrentlibraries etc.).