• 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

  • 相关阅读:
    4.启动虚拟机 设置CentOS7
    Mybatis-09-缓存
    Mybatis-08-动态SQL
    Mybatis-07-多对一和一对多处理
    Mybatis-06-Lombok
    Mybatis-05-使用注解开发
    Mybatis-04-分页
    Mybatis-03-日志
    Mybatis-02-CRUD及配置解析
    Mybatis-01-什么是Mybatis以及第一个Mybatis
  • 原文地址:https://www.cnblogs.com/AloneSword/p/4260994.html
Copyright © 2020-2023  润新知