How to make java.util.Date thread-safe

前端 未结 4 510
无人及你
无人及你 2021-01-04 00:07

As far as i know that java.util.Date is mutable, so it\'s not thread-safe if multiple threads tried to accessing and modifying it. How do we use client-side loc

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 00:41

    You may use the long value (milliseconds since Epoch) instead of a Date instance. Assigning it will be an atomic operation and it would always be coherent.

    But your problem maybe isn't on the Date value itself but on the whole algorithm, meaning the real answer would be based on your real problem.

    Here's a example of buggy operation in a multithread context :

    long time;
    void add(long duration) {
       time += duration; 
    }
    

    The problem here is that you may have two additions in parallel resulting in only one effective addition, because time += duration isn't atomic (it's really time=time+duration).

    Using a long instead of a mutable object isn't enough. In this case you could solve the problem by setting the function as synchronized but other cases could be more tricky.

提交回复
热议问题