1 package org.apache.maven.scm.util;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import java.lang.ref.SoftReference;
23 import java.text.DateFormat;
24 import java.text.FieldPosition;
25 import java.text.ParsePosition;
26 import java.text.SimpleDateFormat;
27 import java.util.Date;
28
29 /**
30 * Thread-safe version of java.text.DateFormat.
31 * You can declare it as a static final variable:
32 * @author Olivier Lamy
33 * <code>
34 * private static final ThreadSafeDateFormat DATE_FORMAT = new ThreadSafeDateFormat( DATE_PATTERN );
35 * </code>
36 */
37 public class ThreadSafeDateFormat
38 extends DateFormat
39 {
40 private static final long serialVersionUID = 3786090697869963812L;
41
42 private final String m_sDateFormat;
43
44 public ThreadSafeDateFormat( String sDateFormat )
45 {
46 m_sDateFormat = sDateFormat;
47 }
48
49 private final ThreadLocal<SoftReference<SimpleDateFormat>> m_formatCache = new ThreadLocal<SoftReference<SimpleDateFormat>>()
50 {
51 public SoftReference<SimpleDateFormat> get()
52 {
53 SoftReference<SimpleDateFormat> softRef = super.get();
54 if ( softRef == null || softRef.get() == null )
55 {
56 softRef = new SoftReference<SimpleDateFormat>( new SimpleDateFormat( m_sDateFormat ) );
57 super.set( softRef );
58 }
59 return softRef;
60 }
61 };
62
63 private DateFormat getDateFormat()
64 {
65 return m_formatCache.get().get();
66 }
67
68 public StringBuffer format( Date date, StringBuffer toAppendTo, FieldPosition fieldPosition )
69 {
70 return getDateFormat().format( date, toAppendTo, fieldPosition );
71 }
72
73 public Date parse( String source, ParsePosition pos )
74 {
75 return getDateFormat().parse( source, pos );
76 }
77 }