illustrating volatile : is this code thread-safe?

前端 未结 6 947
感动是毒
感动是毒 2020-12-17 05:49

I\'m trying to illustrate the use and importance of volatile with an example that would really not give a good result if volatile was omitted.

6条回答
  •  醉酒成梦
    2020-12-17 06:34

    UPDATE My answer is wrong, see answer from irreputable.


    It's not thread-safe, since access to count is not there's only one writer thread. Should there be another writer thread, value of count would be become inconsistent to the number of updates.

    Visibility of count value to main thread is ensured by checking stopped volatile inside getCount method. This is what is called piggybacking on synchronization in Concurrency in practice book.

提交回复
热议问题