So if I have
private static final char[] SOME_CHARS;
Is that thread safe? By that I mean if I have multiple threads referring to the chars in that array (but not changing them), will anything go wrong?
e.g.
private class someThread extends Thread(){
public void run(){
for(int i = 0; i < someIndexInSomeChars;i++){
System.out.println(SOME_CHARS[i]);
}
}
In other words do I need to put the char[] into some sort of Java collection with thread support?
If you don't change them after initialization, it should be fine. (Note that this relies on it being a static final
variable - the way that classes are initialized will ensure that all threads see the initialized array reference correctly.)
Arrays are safe to read from multiple threads. You could even write from multiple threads if you didn't mind seeing stale results - you wouldn't end up "corrupting" the collection itself. (Unlike many other collections, you can't change the size of an array anyway... there's no state to modify other than the elements themselves.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With