线程安全的 SimpleDateFormat

来源:互联网 发布:进存销软件哪些免费 编辑:程序博客网 时间:2024/05/16 15:03
  1. import java.text.SimpleDateFormat;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4.   
  5. public class DateFormatFactory {  
  6.     private static final Map<String, ThreadLocal<SimpleDateFormat>> pool = new HashMap<String, ThreadLocal<SimpleDateFormat>>();  
  7.     private static final Object lock = new Object();  
  8.   
  9.     public static SimpleDateFormat getDateFormat(String pattern) {  
  10.         ThreadLocal<SimpleDateFormat> tl = pool.get(pattern);  
  11.         if (tl == null) {  
  12.             synchronized (lock) {  
  13.                 tl = pool.get(pattern);  
  14.                 if (tl == null) {  
  15.                     final String p = pattern;  
  16.                     tl = new ThreadLocal<SimpleDateFormat>() {  
  17.                         protected synchronized SimpleDateFormat initialValue() {  
  18.                             return new SimpleDateFormat(p);  
  19.                         }  
  20.                     };  
  21.                     pool.put(p, tl);  
  22.                 }  
  23.             }  
  24.         }  
  25.         return tl.get();  
  26.     }  
  27. }  
  28.   
  29. public static Date toDate(String dateStr,String pattern) {  
  30. try{  
  31. return getDateFormat(pattern).parse(dateStr);  
  32. }catch (ParseException e) {  
  33. }  
  34. return null;  
  35. }  
阅读全文
0 0
原创粉丝点击