后台数据发现APP出现一个ANR。追踪发现是日志库SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);出现的。
由于APP一旦启动就会生成大量的日志,每条日志都有日期,该代码会创建很多对象。对于一般需求改性能可以忽略,但是对于频繁创建日志来说,性能有较高要求。
使用ThreadLocal
ThreadLocal是线程的局部变量,是每一个线程所单独持有的,其他线程不能对其进行访问,由于在每个线程中都创建了副本,所以要考虑它对资源的消耗。
1、重写initialValue方法
public class DateUtil {
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static Date parse(String dateStr) throws ParseException {
return threadLocal.get().parse(dateStr);
}
public static String format(Date date) {
return threadLocal.get().format(date);
}
}
2、调用set()方法赋值
public class DateUtil {
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
public static DateFormat getDateFormat()
{
DateFormat df = threadLocal.get();
if(df==null){
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
threadLocal.set(df);
}
return df;
}
public static String formatDate(Date date) throws ParseException {
return getDateFormat().format(date);
}
public static Date parse(String strDate) throws ParseException {
return getDateFormat().parse(strDate);
}
}