Reputation: 5609
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
Upvotes: 2
Views: 1252
Reputation: 26882
Local variables are allocated on the stack, and are local to the thread. Only member fields are shared across threads. So, theWord
and Z
are 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 synchronized
keyword, final
keyword, volatile
keyword, using java.util.concurrent
libraries etc.).
Upvotes: 7
Reputation: 14820
Aside from visibility of variables and lock/synchronization issues for shared variables...
Are variables like "theWord" and "Z" local to the thread
Those variables you ask about are local to the loop, not part of the class or instance, and exist on a per-thread basis, so there won't be any collisions.
Upvotes: 0
Reputation: 3190
Like JOTN says, if the threads are accessing the same objects, then there might be thread collisions.
If the globalArray
variable in this case is shared across the threads, and especially if it or its elements are modified, then it might be wise to use locks/synchronization.
Upvotes: 0
Reputation: 6317
The thread has no impact on what variables are visible. It would be just like you created the class and ran the method without starting a thread. If multiple threads will be accessing the same objects, then you have to look at using locks to make sure they don't step on each other.
Upvotes: 1