Should I volatile the field with synchronized methods?

后端 未结 2 1417
无人共我
无人共我 2021-01-22 19:46

With following class,

// This class should be thread-safe!!!
class BankAccount {

    private long balance; // Should it         


        
2条回答
  •  死守一世寂寞
    2021-01-22 19:56

    No, compared with synchronized keyword, volatile is lightweight.

    volatile can gurantee the reader thread always get fresh balance value, but it can not make balance += amount; atomic. synchronized can do both.

提交回复
热议问题