Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a static final char[] thread safe?

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?

like image 306
praks5432 Avatar asked Oct 29 '12 08:10

praks5432


1 Answers

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.)

like image 155
Jon Skeet Avatar answered Sep 22 '22 03:09

Jon Skeet