0

I have a question about thread-safety. By adding final to the states variable, does it really make the class more thread safe? Since I am not doing anything with states but reading it I could as well forget about final?

class UnsafeStates {
  private String[] states = new String[] { "AK", "AL" /*...*/ };

  public String[] getStates() {
    return states;
  } 
}
Raedwald
  • 46,613
  • 43
  • 151
  • 237
Timo N.
  • 341
  • 3
  • 12
  • 2
    It doesn't prevent anyone from doing `getStates()[0] = "i am evil"`. – Colonel Thirty Two Dec 07 '15 at 14:03
  • 1
    It protects against `states = new...` not on the indexes however. – Emz Dec 07 '15 at 14:33
  • 1
    http://stackoverflow.com/questions/7144915/final-fields-and-thread-safety – Dorus Dec 07 '15 at 14:33
  • To answer the real question (see my link up here): Yes it does make it more thread safe. But no, as pointed out by all the answers below, it's not completely thread safe as the array itself can still be modified. – Dorus Dec 07 '15 at 14:40

3 Answers3

0

Someone can still change the values with final. with states[1] = "something";

Sean Powell
  • 564
  • 4
  • 20
0

Even if you don't change the values of the array, it's not thread-safe because the array is not safely published. The final keyword is needed here to ensure that the initial value of the array is visible to other threads.

fgb
  • 18,439
  • 2
  • 38
  • 52
0

So if i gave back another object with the same values like

    class UnsafeStates {
    private String[] states = new String[] { "AK", "AL" /*...*/ };

    public String[] getStates() {
    String[] states2 = new String[] { "AK", "AL" /*...*/ };
    return states2;
    } 
    }

it would be thread safe, right?

Timo N.
  • 341
  • 3
  • 12