Java double checked locking - Strings

后端 未结 2 600
猫巷女王i
猫巷女王i 2021-01-28 10:52

Given that strings contain final field, does it mean in the context of double checked locking it is not necessary to declare them volatile? E.g.

<
2条回答
  •  情话喂你
    2021-01-28 11:27

    For strings you're right. A string which is declared final cannot be differed and therefore you do not need to synchronize when using it.

    Thats not true for other Objects. Take this little class for example:

    public class BankAccount {
        private int balance = 0;
        public void addMoney(int money) {
            balance+=money;
        }
    }
    

    When you've got a final Object of this class it doesn't mean that nobody can change the fields inside the object. You just can't assign something else to the final variable!

    Conclusion: When accessing final String you don't need to synchronize, when accessing final Objects you might have to, depending on the Object itself.

提交回复
热议问题