When to use volatile and synchronized

前端 未结 5 1866
囚心锁ツ
囚心锁ツ 2020-12-07 16:16

I know there are many questions about this, but I still don\'t quite understand. I know what both of these keywords do, but I can\'t determine which to use in certain scenar

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 16:39

    Note: In your first example, the field serverSocket is actually never initialized in the code you show.

    Regarding synchronization, it depends on whether or not the ServerSocket class is thread safe. (I assume it is, but I have never used it.) If it is, you don't need to synchronize around it.

    In the second example, int variables can be atomically updated so volatile may suffice.

提交回复
热议问题