How to make java.util.Date thread-safe

前端 未结 4 512
无人及你
无人及你 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:38

    The simplest solution is to never modify a Date and never share it. i.e. Only use Date for local variables.

    You can use JodaTime as it has immutable date objects.

    0 讨论(0)
  • 2021-01-04 00:40

    There is no simple solution to create a thread-safe wrapper of Date class. The best way is to synchronize all usages of it's objects by using synchronized blocks.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • In this order, from best to worst:

    1. Not use it at all, check out Java 8's new Date and Time API.

    2. Not use it at all, check out jodatime

    3. Not use it at all, use AtomicLong or immutable primitive long with volatile to represent epoch time

    4. Encapsulate it. Always return defensive copy of Date, never a reference to internal object

    5. Synchronize on Date instance.

    0 讨论(0)
提交回复
热议问题