2

Is bookTokens thread- safe in below code ? I am not pretty sure if values of String array can be read in thread-safe manner ?

public Class Myclass{

    private static final String[] bookTokens = { "amazon", "manning", "book"};

    public static void methodOne(){
    //read values from bookTokens
    }


    public static void methodTwo(){
    //read values from bookTokens
    }

}

6
  • String is immutable therefore they are thread safe, except for StringBuilder Commented Jun 17, 2014 at 2:49
  • 5
    Arrays are not immutable. But if you're only reading, not writing, then it's thread-safe. Commented Jun 17, 2014 at 2:53
  • Possible duplicate Commented Jun 17, 2014 at 2:53
  • 2
    This is not a duplicate of that question. For instance, the example in the other Question involves mutating the array. Commented Jun 17, 2014 at 2:55
  • 1
    I would have used Guava's immutable list, but don't want to overkill if above code is inherently thread-safe. Commented Jun 17, 2014 at 2:59

3 Answers 3

4

In general, an array is not thread-safe.

However, in this case we have an array that will not be updated, and that is initialized in a way that ensures proper synchronization with any thread that subsequently reads it.

Therefore, in this case, the code is thread-safe.

Sign up to request clarification or add additional context in comments.

1 Comment

"...and is initialized in a way that ensures proper synchronization..." Yes. See my response to eitanfar, below, for a reference to a more detailed explanation.
1

This code is only thread safe if you can ensure that there is no code in Myclass that does the equivalent of:

    public static void mutateBookTokens() {
        bookTokens[2] = "addison-wesley";
    }

Comments

0

Any code that only reads values and does not change anything is by nature thread safe, since the data it uses is used as if it was immutable.

2 Comments

See Java Concurrency in Practice by Brian Goetz et al., section 3.5. (Safe Publication), and section 3.5.4 (Effectively Immutable Objects). A technically mutable object (e.g., the array in the example above) that the program never modifies is called effectively immutable. Use of an effectively immutable object is thread safe iff the object was safely published. The array in the example is safely published because it was published via. a final field after it was fully initialized.
+1 for effectively immutable object reference. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.