错误"/>
SimpleDateFormatNumber FormatException 格式化错误
看源码,发现 SimpleDateFormatNumber 不是线程安全的类。
* Date formats are not synchronized.* It is recommended to create separate format instances for each thread.* If multiple threads access a format concurrently, it must be synchronized* externally.
因为,SimpleDateFormat继承了DateFormat,在DateFormat中定义了一个protected属性的 Calendar类的对象:calendar。只是因为Calendar累的概念复杂,牵扯到时区与本地化等等,Jdk的实现中使用了成员变量来传递参数,这就造成在多线程的时候会出现错误。
这样写,在高并发的情况下会出现 java.lang.NumberFormatException: For input string: ""
public class DateUtil {private DateUtil(){}private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public static Date parse(String date) throws ParseException {return DATE_FORMAT.parse(date);} }
改成:
public class DateUtil {private DateUtil(){}public static Date parse(String date) throws ParseException {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);} }
或者:
public class DateUtil {private DateUtil(){}private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public static Date parse(String date) throws ParseException {synchronized(DATE_FORMAT){return DATE_FORMAT.parse(date);}} }
附JDK1.8时间获取
//JDK1.8时间获取当前时间String now = LocalDateTime.now().withNano(0).toString().replace("T", " ");String now = LocalDate.now()+" "+LocalTime.now().withNano(0).toString();
更多推荐
SimpleDateFormatNumber FormatException 格式化错误
发布评论