1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.scm.util;
20
21 import java.lang.ref.SoftReference;
22 import java.text.DateFormat;
23 import java.text.FieldPosition;
24 import java.text.ParsePosition;
25 import java.text.SimpleDateFormat;
26 import java.util.Date;
27
28
29
30
31
32
33
34
35
36 public class ThreadSafeDateFormat extends DateFormat {
37 private static final long serialVersionUID = 3786090697869963812L;
38
39 private final String dateFormat;
40
41 public ThreadSafeDateFormat(String sDateFormat) {
42 dateFormat = sDateFormat;
43 }
44
45 private final ThreadLocal<SoftReference<SimpleDateFormat>> formatCache =
46 new ThreadLocal<SoftReference<SimpleDateFormat>>() {
47 public SoftReference<SimpleDateFormat> get() {
48 SoftReference<SimpleDateFormat> softRef = super.get();
49 if (softRef == null || softRef.get() == null) {
50 softRef = new SoftReference<>(new SimpleDateFormat(dateFormat));
51 super.set(softRef);
52 }
53 return softRef;
54 }
55 };
56
57 private DateFormat getDateFormat() {
58 return formatCache.get().get();
59 }
60
61 public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
62 return getDateFormat().format(date, toAppendTo, fieldPosition);
63 }
64
65 public Date parse(String source, ParsePosition pos) {
66 return getDateFormat().parse(source, pos);
67 }
68 }