View Javadoc
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   *
32   * @author Olivier Lamy
33   * <code>
34   * private static final ThreadSafeDateFormat DATE_FORMAT = new ThreadSafeDateFormat( DATE_PATTERN );
35   * </code>
36   */
37  public class ThreadSafeDateFormat extends DateFormat {
38      private static final long serialVersionUID = 3786090697869963812L;
39  
40      private final String dateFormat;
41  
42      public ThreadSafeDateFormat(String sDateFormat) {
43          dateFormat = sDateFormat;
44      }
45  
46      private final ThreadLocal<SoftReference<SimpleDateFormat>> formatCache =
47              new ThreadLocal<SoftReference<SimpleDateFormat>>() {
48                  public SoftReference<SimpleDateFormat> get() {
49                      SoftReference<SimpleDateFormat> softRef = super.get();
50                      if (softRef == null || softRef.get() == null) {
51                          softRef = new SoftReference<>(new SimpleDateFormat(dateFormat));
52                          super.set(softRef);
53                      }
54                      return softRef;
55                  }
56              };
57  
58      private DateFormat getDateFormat() {
59          return formatCache.get().get();
60      }
61  
62      public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
63          return getDateFormat().format(date, toAppendTo, fieldPosition);
64      }
65  
66      public Date parse(String source, ParsePosition pos) {
67          return getDateFormat().parse(source, pos);
68      }
69  }