1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
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 * Thread-safe version of java.text.DateFormat.
30 * You can declare it as a static final variable:
31 * @author Olivier Lamy
32 * <code>
33 * private static final ThreadSafeDateFormat DATE_FORMAT = new ThreadSafeDateFormat( DATE_PATTERN );
34 * </code>
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<SimpleDateFormat>(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 }