Difference between synchronization of field reads and volatile

前端 未结 3 1626
無奈伤痛
無奈伤痛 2020-12-06 17:57

In a nice article with some concurrency tips, an example was optimized to the following lines:

double getBalance() {
    Account acct = verify(name, password         


        
3条回答
  •  情歌与酒
    2020-12-06 18:19

    If multiple threads are modifying and accessing the data, synchronized guarantees data consistency among multiple threads .

    if single thread is modifying the data and multiple threads try to read the latest value of data, use volatile construct.

    But for above code, volatile does not guaranty memory consistency if multiple threds modify balance. AtomicReference with Double type serves your purpose.

    Related SE question:

    Difference between volatile and synchronized in Java

提交回复
热议问题