• SimpleDateFormat in Java is not Thread-Safe Use Carefully


    SimpleDateFormat in Java  very common and used to format Date to String and parse String into Date in Java but it can cause very subtle and hard to debug issues if not used carefully because DateFormat and SimpleDateFormat both are not thread-safe and buggy. call to format() and parse() method mutate state of DateFormat class and should be synchronized externally in order to avoid any issue. here are few points which you should take care while using SimpleDateFormat in Java:

    SimpleDateFormat in Java is not Thread-Safe

    1) Use local DateFormat or SimpleDateFormat objects for converting or formatting dates in Java. Making them local ensure that they will not be shared between multiple Threads.
     
    2) If you are sharing Date for SimpleDateFormat class in Java then you need to externally synchronize
    call to format() and parse() method as they mutate state of DateFormat object and can create subtle and hard
    to fix bugs while formatting Strings or creating dates in Java. Best is to avoid sharing of DateFormat class altogether.
     
    3) If you have option use JODA date time library for your date and time related operation. its easy to understand and portable with Java Date API and solves all thread-safety issues associated with SimpleDateFormat in Java.
     
    4) Another good alternative of SimpleDateFormat in Java is Apaches' commons.lang package which hold a class called  FastDateFormat utility class and thread-safe alternative of SimpleDateFormat in Java.
     
    5) Another approach of synchronizing DateFormat and SimpleDateFormat is using ThreadLocal, which create SimpleDateFormat on per Thread basis but it can be source of severe memory leak and java.lang.OutOfMemoryError if not used carefully. so avoid until you don't have any other option.
     
    That’s all on SimpleDateFormat in Java. Many people has pointed out flaw on design of Format class but unfortunately Sun or Oracle has not addressed them in any release not even in JDK7. SimpleDateFormat is still first choice because of its availability on standard library but should be used carefully.



    Read more: http://javarevisited.blogspot.com/2012/03/simpledateformat-in-java-is-not-thread.html#ixzz3QDZXPBbq

  • 相关阅读:
    MVC 小demo
    单例模式
    简单工厂模式
    有关ajax中的URL问题
    SqlHelper++
    C# 操作XML
    C# 注册DLL(使用cmd)
    图片延迟加载库Layzr
    解决Ajax跨域问题:Origin xx is not allowed by Access-Control-Allow-Origin.
    HTML5 + SOCKET视频传输
  • 原文地址:https://www.cnblogs.com/AloneSword/p/4260994.html
Copyright © 2020-2023  润新知