8

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?

4

1 回答 1

10

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

于 2012-10-29T08:02:40.007 回答