Java multi-threading atomic reference assignment

前端 未结 4 1237
别跟我提以往
别跟我提以往 2020-12-08 03:02

I have a cache which I implemented using a simeple HashMap. like -

HashMap cache = new HashMap();

4条回答
  •  孤街浪徒
    2020-12-08 03:48

    You should mark the cache as volatile.

    While you note that other threads may continue using a stale cache for "a long time" you should note that, without a synchronization edge, they are likely to continue using the stale cache forever. That's probably not the desired behavior.

    In order of preference (mostly due to readability):

    • Update the field in a synchronized method
    • Use AtomicReference>
    • Use volatile

    See also this question.

提交回复
热议问题